The Balance
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 6235 Accepted Submission(s): 2564
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
母函数,但是这一点要讲一下!不同之处,这里又多了一个减法
(除法),所以无从下手,一开始用深搜,数据太大,之间崩溃
了!
#include<cstdio>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int n,sum,b[100005],a[1005],j,flag,sum1,c[100005];
bool visit[1005];
int compare(int a,int b)
{
return a>b;
}
void dfs(int pos)
{
int i;
for(i=pos;i<n;i++)
{
sum1+=a[i];
if(sum1==a[0])
{
flag++;
}
if(flag==2)
{
return;
}
b[j++]=sum1;
visit[i]=1;
dfs(i+1);
sum1-=a[i];
visit[i]=0;
}
}
int main()
{
int i,k,x,y,flag2,sum2,sum3;
while(cin>>n)
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
memset(visit,0,sizeof(visit));
x=flag=j=sum1=sum=0;
for(i=0;i<n;i++)
{
cin>>a[i];
sum+=a[i];
}
sort(a,a+n,compare);
dfs(0);
/* for(i=0;i<n;i++)
{
sum2=0;
for(k=i+1;k<n;k++)
{
sum3=a[k];
sum2+=sum3;
if(sum2<a[i])
{
b[j++]=a[i]-sum2;
}
if(sum3<a[i]&&sum3!=sum2)
{
b[j++]=a[i]-sum3;
}
}
}*/
for(i=1;i<=sum;i++)
{
y=0;
for(k=0;k<j;k++)
{
if(i==b[k])
{
y=1;
break;
}
}
if(y==0)
{
c[x++]=i;
}
}
if(x==0)
{
cout<<0<<endl;
}
else
{
cout<<x<<endl;
for(i=0;i<x-1;i++)
{
cout<<c[i]<<" ";
}
cout<<c[x-1]<<endl;
}
}
}
看到网上的代码,感觉写的很好!也深深地体会到了母函数#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int a[105],b[10005],c[10005],ans[10005];
int main()
{
int i,j,f,n,k,sum;
while(cin>>n)
{
f=sum=0;
for(i=1;i<=n;i++)
{
cin>>a[i];
sum+=a[i];
}
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
b[0]=1;b[a[1]]=1;//初始化
for(i=2;i<=n;i++)
{
for(j=0;j<=sum;j++)
{
for(k=0;k+j<=sum&&k<=a[i];k+=a[i])//这里之所以限制,所以设置k<=a[i]实际上是为了避免多次加a[i]
{
c[k+j]+=b[j];
c[abs(j-k)]+=b[j];
}
}
for(j=0;j<=sum;j++)
{
b[j]=c[j];
c[j]=0;
}
}
for(i=1;i<=sum;i++)
{
if(!b[i])
{
ans[f++]=i;
}
}
if(f==0)
{
cout<<0<<endl;
}
else
{
cout<<f<<endl;
for(i=0;i<f-1;i++)
{
cout<<ans[i]<<" ";
}
cout<<ans[f-1]<<endl;
}
}
}