首页 > 其他分享 >D - Money in Hand -- 动态规划

D - Money in Hand -- 动态规划

时间:2023-01-22 22:33:11浏览次数:49  
标签:-- Money coins Hand int ai yuan dp

D - Money in Hand

https://atcoder.jp/contests/abc286/tasks/abc286_d

 

思路

dp[i][j]:
for j yuan,
find if it is possible to get j yuan
with the first i coins.

dp[i][j] =
    dp[i-1][j]
    | dp[i-1][j-ai]
    | dp[i-1][j-2ai]
    ...
    | dp[i-1][j-bi*ai]

Code

https://atcoder.jp/contests/abc286/submissions/38268561

const int N = 50;
const int X = 1e4;
 
int n, x;
 
/*
ai -- a yuan of one coin
bi -- b coins of a yuan
*/
int a[60];
int b[60];
 
/*
dp[i][j]:
for j yuan,
find if it is possible to get j yuan
with the first i coins.
 
i = 1 --> N
j = 1 --> X
 
dp[i][j] =
    dp[i-1][j]
    | dp[i-1][j-ai]
    | dp[i-1][j-2ai]
    ...
    | dp[i-1][j-bi*ai]
    
check if dp[n][x] == true ?
*/
 
bool dp[N+1][X+1];
 
int main()
{
    cin >> n >> x;
    for(int i=1; i<=n; i++){
        cin >> a[i] >> b[i];
    }
 
    /*
    for 0 yuan
    if no coins are selected,
    0 yuan is meeted.
    there is one way to make it.
    */
    dp[0][0] = true;
 
    /*
    for 0 yuan,
    as of the first i coins
    there are one way to get 0 yuan
    ie, no selection of any coin.
    */
    for(int i=1; i<=N; i++){
        dp[i][0] = true;
    }
 
    /*
    for any j yuan
    if no one coin is selected
    there is no way to get j yuan.
    */
    for(int j=1; j<=X; j++){
        dp[0][j] = false;
    }
    
    /*
    i = 1 --> n
    j = 1 --> x
    
    dp[i][j] =
        dp[i-1][j]
        | dp[i-1][j-ai]
        | dp[i-1][j-2ai]
        ...
        | dp[i-1][j-bi*ai]
    */
    for(int i=1; i<=n; i++){
        int ai = a[i];
        int bi = b[i];
        
        for(int j=1; j<=x; j++){
            dp[i][j] = 0;
            
            for(int k=0; k<=bi&&k*ai<=j; k++){
                dp[i][j] |= dp[i-1][j-k*ai];
            }
        }
    }
 
    if (dp[n][x] > 0){
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }
 
    return 0;
}
 

 

标签:--,Money,coins,Hand,int,ai,yuan,dp
From: https://www.cnblogs.com/lightsong/p/17064754.html

相关文章