集训第五周 动态规划 K题 背包

K - 背包
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
Submit Status

Description

Now you are asked to measure a dose of medicine with a balance and a number of weights. Certainly it is not always achievable. So you should find out the qualities which cannot be measured from the range [1,S]. S is the total quality of all the weights. 
 

Input

The input consists of multiple test cases, and each case begins with a single positive integer N (1<=N<=100) on a line by itself indicating the number of weights you have. Followed by N integers Ai (1<=i<=N), indicating the quality of each weight where 1<=Ai<=100. 
 

Output

For each input set, you should first print a line specifying the number of qualities which cannot be measured. Then print another line which consists all the irrealizable qualities if the number is not zero. 
 

Sample Input

3 1 2 4 3 9 2 1
 

Sample Output

0 2 4 5
 
 
这道题可以使用DP做,dp(i)代表i这个数字是否可称,dp(i)=(( dp(j)==1 && 1<j<sum )     j==i + || - 新加入的数字 ?)
 
#include"iostream"
#include"algorithm"
#include"cstring"
using namespace std;

const int maxn=10010;

int dp[maxn],ok[maxn],ans[maxn];

int main()
{
    int sum,n,temp;

    while(cin>>n)
    {
        memset(dp,0,sizeof(dp));
        dp[0]=1;
        sum=0;
        for(int i=1;i<=n;i++)
        {
            cin>>temp;
            memset(ok,0,sizeof(ok));
            sum+=temp;
            for(int j=0;j<=sum;j++) if(dp[j])
            {
                ok[j+temp]=1;
                ok[abs(j-temp)]=1;
            }
            for(int j=1;j<=sum;j++) if(ok[j])
            dp[j]=1;
        }
        int top=0;
        for(int i=1;i<=sum;i++)
        {
            if(dp[i]==0) ans[top++]=i;
        }
        cout<<top<<endl;
        if(top)
        {
        for(int j=0;j<top-1;j++) cout<<ans[j]<<" ";
        cout<<ans[top-1]<<endl;
        }
    }
    return 0;
}
你好

 

posted @ 2015-08-13 21:40  江南何采莲  阅读(144)  评论(0编辑  收藏  举报