标签:
3 1 2 4Behind FJ‘s back, the cows have started playing a more difficult game, in which they try to determine the starting sequence from only the final total and the number N. Unfortunately, the game is a bit above FJ‘s mental arithmetic capabilities.
4 3 6
7 9
16
Input
Output
Sample Input
4 16
Sample Output
3 1 2 4
Hint
1 #include <cstdio> 2 #include <cstring> 3 using namespace std; 4 int a[15][15],n,sum,vis[15],ans[15]; 5 bool f; 6 void setnum ()//生成杨辉三角形 7 { 8 for (int i=0;i<n;++i) 9 { 10 a[i][0]=1; 11 a[i][i]=1; 12 } 13 for (int i=2;i<n;++i) 14 for (int j=1;j<i;++j) 15 a[i][j]=a[i-1][j-1]+a[i-1][j]; 16 } 17 void printAns () 18 { 19 for (int i=0;i<n;++i) 20 { 21 printf("%d",ans[i]); 22 if (i!=n-1) 23 printf(" "); 24 } 25 printf("\n"); 26 } 27 void dfs (int nowsum,int step)//这样的搜索是刚好字典序的 28 { 29 if (step==n) 30 { 31 if (nowsum==sum) 32 { 33 f=true; 34 printAns(); 35 } 36 return ; 37 } 38 if (f||nowsum>sum) 39 return ; 40 for (int i=1;i<=n;++i) 41 { 42 if (vis[i]) 43 continue; 44 vis[i]=1; 45 ans[step]=i; 46 dfs(nowsum+i*a[n-1][step],step+1); 47 vis[i]=0;//每次搜完以后要清空状态 48 } 49 } 50 int main() 51 { 52 scanf("%d%d",&n,&sum); 53 setnum(); 54 f=false; 55 memset(vis,0,sizeof vis); 56 memset(ans,0,sizeof ans); 57 dfs(0,0); 58 return 0; 59 }
POJ 3187 Backward Digit Sums (dfs,杨辉三角形性质)
标签:
原文地址:http://www.cnblogs.com/agenthtb/p/5889972.html