Eric
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # DP dynamic programming(動態規劃) ## 01背包問題 對於每個物品可選與不選,先利用這點找出轉移方程,當然我們要選出最大值,所以在此選擇裡選出的最大值就是該項目答案 ```cpp= int chose=dp(n-1,w-L[n])+S[n]; //選此項目,加上該項目的利益 int notchose=dp(n-1,w); //不選此項目,=前一個項目的答案 return max(chose,notchose); ``` 接著再利用紀錄重複子問題的答案,加速該題的計算過程 ```cpp= if(dpa[n][w]!=0) return dpa[n][w]; int chose=dp(n-1,w-W[n])+P[n]; int notchose=dp(n-1,w); dpa[n][w]=max(chose,notchose); return dpa[n][w]; ``` 最後再加上邊界判斷的判斷就完成了 ```cpp= int dp(int n,int w){ if(w<0) return -1e9; if(n==0) return 0; if(dpa[n][w]!=0) return dpa[n][w]; int chose=dp(n-1,w-W[n])+P[n]; int notchose=dp(n-1,w); dpa[n][w]=max(chose,notchose); return dpa[n][w]; } ``` 由遞迴式(top-down)轉變成迴圈式(botton-up) ```cpp= for(int n=1;n<=N;n++){ for(int w=0;w<=M;w++){ int chose; if(w-W[n]>=0) chose=dp[n-1][w-W[n]]+P[n]; else chose=INT_MIN; //如果背包放不下此物品,就不能選,要給他一個很小的值這樣取max才不會取到 int notchose=dp[n-1][w]; dp[n][w]=max(chose,notchose); } } ``` 簡化為一為陣列 因為每次會需要左上方的陣列,如果從前面掃的話會會把後面要存取的數值覆蓋掉,所以要從後面掃 ```cpp= for(int n=1;n<=N;n++){ for(int w=M;w>0;w--){ int chose=-1e9; if(w-W[n]>=0) chose=dp[w-W[n]]+P[n]; int notchose=dp[w]; dp[w]=max(chose,notchose); } } ``` 如果放進去了哪些物件可以逆推回去 ```cpp= int BigM=M; int ans[10000]={0}; //紀錄有沒有放進去 for(int i=N;i>0;i--){ if(BigM-W[i]>=0 && dp[i][BigM]==dp[i-1][BigM-W[i]]+P[i]){ ans[i]=1; //記錄這個放進去物件的點 BigM-=W[i]; //扣掉此物件的重量繼續找下一個物品 } } for(int i=1;i<=N;i++){ if(ans[i]) cout << L[i] << " "; } ``` 一維陣列如果要求哪些元素被放進去要開一個陣列記錄 ```cpp= bool ans[100][100]={0}; //紀錄有沒有放進去 for(int n=1;n<=N;n++){ for(int w=M;w>0;w--){ if(dp[w-W[n]]+P[n] > dp[w]){ dp[w]=dp[w-W[n]]+P[n]; ans[n][w]=true; //第n項物品在w的時候有放進去 } } } for(int i=N,BigM=M;i>0;i--){ if(ans[i][BigM]){ cout << i << " "; BigM-=W[i]; } } ``` ## coin change(最少硬幣) 對於每個amount都可以是(amount-貨幣面額)的情況再+1,+1就是該貨幣面額,所以狀態轉移方程為 ```cpp= dp[i]=min(dp[i],dp(amount-coin[i])+1); ``` 所以在初始化的時候可以把陣列設成amount+1,但不包刮dp[0] (因為在0元的時候能換到的情況是0),這樣在取min的時候如果有合法的情況都會比amount+1小,(能換到最多錢的情況是amount個1塊)),然後更新到dp裡面,最後要判斷有沒有任何方法可以換的時候就看dp[amount],如果dp[amount]跟我們初始化的值一樣代表沒有情況能成立,否則dp[amount]是最佳解 bottom-up ```cpp= int coinChange(vector<int>& coins, int amount) { vector<int> dp(amount+1,amount+1); dp[0]=0; for(int i=1;i<=amount;i++){ for(int j=0;j<coins.size();j++){ if(i-coins[j]>=0) dp[i]=min(dp[i],dp[i-coins[j]]+1); } } return dp[amount]>amount?-1:dp[amount]; } ``` Top-down ```cpp= int dpf(int amount,vector<int>& cache){ if(amount<0) return 1e9; if(amount==0) return 0; if(cache[amount]) return cache[amount]; int mi=amount+1; for(int i=0;i<coin.size();i++){ mi=min(mi,dpf(amount-coin[i],cache)+1); } return cache[amount]=mi; } ``` ## coin change(幾種組合) dp[i]項的組合數就是dp[i-c]的組合相加,c = for c in range coin,要注意兩個迴圈內外的順序,如果是對於第i個點一次跑完所有硬幣的時候,後面會因為重複的組合而導致答案錯誤,例如3={2,1}&{1,2},所必需把該硬幣拷完才換下一個,否則會出現只有順序顛倒但元素卻一樣的組合 ```cpp= d253. 00674 - Coin Change AC (22ms, 368KB) #include <bits/stdc++.h> using namespace std; int coin[]={1,5,10,25,50}; int coinsize=5; int main(){ int n; vector<int> dp(7490,0); dp[0]=1; for(int j=0;j<coinsize;j++){ for(int i=1;i<=7489;i++){ if(i-coin[j]>=0){ dp[i]+=dp[i-coin[j]]; } } } while(cin >> n){ cout << dp[n] << '\n'; } return 0; } ``` 另外特別注意的點是內迴圈數值的順序: 如果coin裡的元素是可以重複的,內詢圈的順序要從小到大,因為這樣才會把小的帶到大的; 如果coin裡的元素不能重複,內迴圈要從大跑到小,這樣才不會把小的已算過的該元素再算到大的,這樣就會算兩次; (左邊元素可重複,右邊元素不可重複) ![](https://i.imgur.com/t0uFDDZ.png)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully