标签:ogr using less tee ini const examples find put
Input
The input data consists of several test cases.
The
first line of the input will contain an integer N, which is the number of test
cases.
Each test case will first contain an integer M (1<=M<=30),
which is the number of integers in the set, and then is followed by M distinct
positive integers in the same line.
Output
For each test case, you are supposed to output all the
additive equations of the set. These equations will be sorted according to their
lengths first( i.e, the number of integer being summed), and then the equations
with the same length will be sorted according to the numbers from left to right,
just like the sample output shows. When there is no such equation, simply output
"Can‘t find any equations." in a line. Print a blank line after each test
case.
3 3 1 2 3 3 1 2 5 6 1 2 3 5 4 6
Output for the Sample Input
1+2=3 Can‘t find any equations. 1+2=3 1+3=4 1+4=5 1+5=6 2+3=5 2+4=6 1+2+3=6
题意:按顺序列举出所有满足集合内的数个元素之和仍然属于该集合的等式.而顺序是元素数目少的优先,数目相同的按字典序排列.
分析:搜索+减枝.用par数组来判断“和”是否属于该集合,用sum数组来存放等式左边,用ans来存放等式右边.
1 #include <cstdio> 2 #include <algorithm> 3 #include <cstring> 4 using namespace std; 5 int n,m,ans,pos,len; 6 int flag; 7 const int maxn=110; 8 int a[maxn],vis[maxn]; 9 int sum[maxn]; 10 int par[11000]; 11 void dfs(int m,int len) 12 { 13 if(m>=n) 14 return ; 15 if(pos>n) 16 return ; 17 if(ans>a[n-1]) 18 return ; 19 if(par[ans]==1&&m>1&&m==len) 20 { 21 flag=1; 22 for(int j=0;j<m-1;j++) 23 { 24 printf("%d+",sum[j]); 25 } 26 printf("%d=%d\n",sum[m-1],ans); 27 return ; 28 } 29 for(int i=pos;i<n;i++) 30 { 31 if(vis[i]==0) 32 { 33 vis[i]=1; 34 sum[m]=a[i]; 35 ans+=sum[m]; 36 pos=i; 37 dfs(m+1,len); 38 39 vis[i]=0; 40 ans-=sum[m]; 41 } 42 } 43 } 44 void init() 45 { 46 memset(par,0,sizeof(par)); 47 memset(vis,0,sizeof(vis)); 48 ans=pos=flag=m=0; 49 } 50 void solve() 51 { 52 for(int i=2;i<n;i++) 53 { 54 pos=0; 55 dfs(0,i); 56 } 57 58 if(!flag) 59 printf("Can‘t find any equations.\n\n"); 60 else 61 printf("\n"); 62 } 63 int main() 64 { 65 int t; 66 scanf("%d",&t); 67 while(t--) 68 { 69 scanf("%d",&n); 70 init(); 71 for(int i=0;i<n;i++) 72 { 73 scanf("%d",&a[i]); 74 par[a[i]]=1; 75 } 76 sort(a,a+n); 77 solve(); 78 } 79 return 0; 80 }
标签:ogr using less tee ini const examples find put
原文地址:http://www.cnblogs.com/onlyli/p/7204094.html