Sum It Up
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 4746 Accepted Submission(s): 2470
4 6 4 3 2 2 1 1 5 3 2 1 1 400 12 50 50 50 50 50 50 25 25 25 25 25 25 0 0
Sums of 4: 4 3+1 2+2 2+1+1 Sums of 5: NONE Sums of 400: 50+50+50+50+50+50+25+25+25+25 50+50+50+50+50+25+25+25+25+25+25
DFS问题不多说,需要注意是他不能出现重复,且每个数字的数目要从高到底降序的形式出现。而且看题还要仔细点,没有结果的情况下,Sum of :还是要输出的。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int cmp(int a,int b)
{
return a>b;
}
int n,sum,arr[15];
int xulie1[10000][15],xulie2[15];
int xulienum;
bool choose[15];
bool exist;
void out()
{
int i,s=0;
for(i=0;i<n;i++)
{
if(choose[i])
{
s+=arr[i];
}
}
int j=0;
if(s==sum)
{
memset(xulie2,0,sizeof(xulie2));
for(i=0;i<n;i++) if(choose[i]) xulie2[j++]=arr[i];
bool pan=false;
for(j=0;j<xulienum;j++)
{
for(i=0;i<n;i++)
{
if(xulie1[j][i]!=xulie2[i]) break;
}
if(i==n) pan=true;
}
if(pan) return ;
else
{
for(i=0;i<n;i++) xulie1[xulienum][i]=xulie2[i];
xulienum++;
}
if(!exist)
{
exist=true;
//cout<<"Sums of "<<sum<<":"<<endl;
}
for(i=0;i<n;i++)
{
if(choose[i]) {cout<<arr[i];break;}
}
for(i++;i<n;i++)
{
if(choose[i]) cout<<"+"<<arr[i];
}
cout<<endl;
}
}
void DFS(int i)
{
if(i==n)
{
out();
return;
}
choose[i]=true;
DFS(i+1);
choose[i]=false;
DFS(i+1);
}
int main(int argc, char *argv[])
{
while(cin>>sum>>n)
{
if(sum==0&&n==0) break;
int i;
memset(choose,false,sizeof(choose));
memset(xulie1,0,sizeof(xulie1));
memset(xulie2,0,sizeof(xulie2));
xulienum=0;
exist=false;
for(i=0;i<n;i++)
{
cin>>arr[i];
}
sort(arr,arr+n,cmp);
cout<<"Sums of "<<sum<<":"<<endl;
DFS(0);
if(!exist) cout<<"NONE"<<endl;
/*for(i=0;i<xulienum;i++)
{
for(int j=0;j<n;j++)
{
cout<<xulie1[i][j]<<" ";
}
cout<<endl;
}*/
}
return 0;
}