- 新年趣事之打牌
- @ 2018-02-02 10:50:45
7AC 2WA 1RE
#include <algorithm>
#include <cstdio>
using namespace std;
int sum,totalw,n,ans[1001],dp[1000001],pre[1000001],w[1001];
int main() {
    scanf("%d%d",&totalw,&n);
    for (int i = 1;i <= n;i++) {
        scanf("%d",&w[i]);
        sum += w[i];
    }
    totalw = sum-totalw;
    dp[0] = 1;
    for (int i = 1;i <= n;i++)
        for (int j = totalw;j >= w[i];j--) {
            dp[j] += dp[j-w[i]];
            pre[j] = i;
        }
    dp[0] = 0;
    if (dp[totalw] == 0) printf("0");
    else if (dp[totalw] > 1) printf("-1");
    else {
        int now = totalw,cnt = 0;
        while (now) {
            ans[++cnt] = pre[now];
            now -= w[pre[now]];
        }
        sort(ans+1,ans+cnt+1);
        for (int i = 1;i <= cnt;i++) printf("%d%c",ans[i],i == cnt ? '\n' : ' ');
    }
    return 0;
}
1 条评论
- 
  你的名字 LV 3 @ 2018-02-02 13:35:21您A了吗 
 代码中pre数组不能这样转移(在前一个状态为空的情况下)
- 1