HDU1258 DFS
题意:求n个数中的某些数的和等于t,并输出
dfs
记录下已经输出过的,然后每次比较一下,这样就能避免重复
View Code
1 #include<stdio.h> 2 #include<string.h> 3 #include<stdlib.h> 4 #include<algorithm> 5 using namespace std; 6 const int maxn = 15; 7 const int maxm = 500005; 8 int num[ maxn ]; 9 int vis[ maxn ]; 10 int ans[ maxn ]; 11 int t,n; 12 int flag; 13 int new_start; 14 struct node{ 15 int cnt; 16 int ans[ maxn ]; 17 }my[ maxm ],temp; 18 int cnt_my; 19 int judge( ){ 20 sort( temp.ans,temp.ans+temp.cnt ); 21 for( int i=0;i<cnt_my;i++ ){ 22 if( temp.cnt==my[i].cnt ){ 23 int k; 24 int fff=1; 25 for( k=0;k<temp.cnt;k++ ){ 26 if( temp.ans[k]==my[i].ans[k] ) 27 {} 28 else{ 29 fff=-1; 30 break; 31 } 32 } 33 if( fff==1 ) 34 return i;//exist 35 } 36 } 37 for( int i=0;i<temp.cnt;i++ ){ 38 my[ cnt_my ].ans[ i ]=temp.ans[i]; 39 } 40 my[ cnt_my ].cnt=temp.cnt; 41 cnt_my++; 42 return -1; 43 } 44 int judge2(int p){ 45 int sum=0; 46 for( int i=p;i<=n;i++ ){ 47 sum+=num[i]; 48 } 49 return sum; 50 } 51 void dfs( int pos,int sum,int cnt ){ 52 if( sum==t ){ 53 temp.cnt=cnt; 54 for( int i=0;i<cnt;i++ ){ 55 temp.ans[i]=ans[i]; 56 } 57 if( judge()==-1 ){ 58 flag=1; 59 for( int i=0;i<cnt;i++ ){ 60 if( i==0 ) printf("%d",ans[i]); 61 else printf("+%d",ans[i]); 62 } 63 printf("\n"); 64 } 65 //new_start++; 66 return ; 67 } 68 for( int i=new_start;i<=n;i++ ){ 69 if( vis[ i ]==0&&(sum+num[i])<=t ){ 70 int ttt=judge2( i ); 71 for( int k=0;k<cnt;k++ ) 72 ttt+=ans[k]; 73 if( ttt<t ) return ; 74 vis[ i ]=1; 75 ans[ cnt ]=num[i]; 76 dfs( i,sum+num[i],cnt+1 ); 77 vis[ i ]=0; 78 } 79 } 80 return ; 81 } 82 83 int main(){ 84 while( scanf("%d%d",&t,&n),n ){ 85 for( int i=1;i<=n;i++ ){ 86 scanf("%d",&num[ i ]); 87 vis[i]=0; 88 } 89 flag=-1; 90 cnt_my=0; 91 printf("Sums of %d:\n",t); 92 for( int i=1;i<=n;i++ ){ 93 if( num[i]>t ) { 94 vis[i]=1; 95 continue; 96 } 97 if( num[i]==t&&flag==-1 ){//在这个判断条件上wa了一次!!!flag!=-1 98 flag=1; 99 vis[i]=1; 100 my[ 0 ].cnt=1; 101 my[ 0 ].ans[0]=t; 102 cnt_my++; 103 printf("%d\n",t); 104 continue; 105 } 106 if( num[i]==t&&flag==1 ){ 107 vis[i]=1; 108 continue; 109 } 110 new_start=i; 111 dfs( i,0,0 );//pos sum cnt 112 break; 113 } 114 if( flag==-1 ) 115 printf("NONE\n"); 116 //printf("end\n"); 117 } 118 return 0; 119 }
keep moving...