HDU 1709

The Balance

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3218    Accepted Submission(s): 1280


Problem 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
 

这题其实思路是非常清晰的,就是应该要分成两个步骤来求解,(1)正常的求母函数的过程与方法(2)由于两两和值的差值也是能够被称出的,因此我们必须要把这一部分也求出来。

就我个人,(1)自然没什么可讲,但一开始(2)步骤想的太过繁琐,结果。。。然后在他人启发下,我们可以设置一个数组,将所有的差值的全存入其中,然后用遍历的思想去找出在此之外的。(其实我的想法也是这样,只不过,更杂乱一些,然后遗漏了一些本应有的)。

其实,母函数是很模板化的。。。我感觉

 

View Code
 1 #include"iostream"

 2 using namespace std;

 3 int main()

 4 {

 5     int c1[10005],c2[10005],a[10005],b[10005],c[10005];

 6     int i,j,k,n,sum,p;

 7     while(cin>>n)

 8     {

 9         sum=0;

10         for(i=0;i<n;i++)

11         {

12             cin>>a[i];

13             sum+=a[i];

14         }

15         for(i=1;i<=sum;i++)

16         {

17             c1[i]=0;

18             c2[i]=0;

19             b[i]=0;

20             c[i]=0;

21         }

22         for(i=0;i<=1;i++)

23             c1[i*a[0]]=a[0];

24         for(i=1;i<n;i++)

25         {

26             for(j=0;j<=sum;j++)

27                 for(k=0;k*a[i]+j<=sum&&k<=1;k++)

28                     c2[k*a[i]+j]+=c1[j];

29             for(j=0;j<=sum;j++)

30             {

31                 c1[j]=c2[j];

32                 c2[j]=0;

33             }

34         }       //到这里完成第一部分

35         for(i=sum;i>0;i--)

36         {

37             if(!c1[i])

38                 continue;

39             for(j=1;j<i;j++)

40             {

41                 if(!c1[j])

42                     continue;

43                 b[i-j]=1;

44             }

45         }//这里是把能有的差值用这种方式找出来

46         p=0;

47         for(i=1;i<=sum;i++)

48         {

49             if(!c1[i]&&!b[i])//s数组中为1的是能够被称出来的(出了data中的以外)

50                 c[p++]=i;

51         }

52         cout<<p<<endl;

53         if(p)

54         {

55             for(i=0;i<p-1;i++)

56                 cout<<c[i]<<' ';

57             cout<<c[i]<<endl;

58         }

59     }

60     return 0;

61 }

 

 

你可能感兴趣的:(HDU)