牛客競賽——小M和天平(簡單dp)

題目鏈接:https://ac.nowcoder.com/acm/problem/13586

 思路:首先所有能稱出的重量均在0~10000之間

#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
#include <queue>
#include <cstdio>
#include <string>
#include <stack>
#include <set>
#define IOS ios::sync_with_stdio(false), cin.tie(0)
using namespace std;
typedef long long ll;

namespace ak{
    //dp[i][j]前i個石子能否稱出j的重量
    int dp[110][10010];
    int n,m,k;
    int a[110];
    //核心dp
    void getdp(){
        memset(dp,0,sizeof(dp));
        dp[0][0]=1;
        for(int i=1;i<=n;i++){
            //所有可能稱出的重量不可能超過10000;
            for(int j=0;j<=10000;j++){
                if(dp[i-1][j]){//如果前i-1個石子能稱出j的重量
                    dp[i][j]=1;//不放該石子
                    dp[i][j+a[i]]=1;//放疊加的一邊
                    dp[i][abs(j-a[i])]=1;//放抵消的一邊
                }
            }
        }
    }
    void query(){
        cin>>m;
        while(m--){
            cin>>k;
            if(k<=10000&&dp[n][k]){
                cout<<"YES"<<endl;
            }
            else cout<<"NO"<<endl;
        }
    }
    void work(){
        while(cin>>n){
            for(int i=1;i<=n;i++){
              cin>>a[i];
            }
            getdp();
            query();
        }
    }
}

int main(){
    IOS;
    ak::work();
    getchar();
    getchar();
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章