Ideas
Using the Yang Hui triangle, each number is added equal to the number it corresponds to in the Yang Hui Triangle. Note that the meaning of this problem is that the bottom level is the full ordering of N, not the 1. 10 is all you can. When the Yang Hui triangle was generated, the first time I used a two-cycle simulation to generate, later learned that the Yang Hui Triangle, the nth row K number is Cnk. However, in the second program, my Yang Hui triangle is not preprocessed, resulting in a lot of wasted time. Two methods of deep search and STL are used. Deep search is obviously faster than next_permuation because it can be pruned.
1 /*232K 0MS*/ 2 /*simulation + Deep Search*/3#include <iostream>4#include <cstdio>5 using namespacestd;6 Const intmaxn=Ten+5;7 intn,sum;8 intA[MAXN][MAXN];9 intANS[MAXN];Ten intVIS[MAXN]; One intF; A - voidGettri () - { the for(intI=0; i<n;i++) - { -a[i][0]=1; -a[i][i]=1; + } - for(intI=2; i<n;i++) + for(intj=1; j<i;j++) Aa[i][j]=a[i-1][j-1]+a[i-1][j]; at } - - voidprint () - { - for(intI=0; i<n;i++) cout<<ans[i]<<' '; -cout<<Endl; in } - to voidGetnum (intStepintnowsum) + { - if(step==N) the { * if(nowsum==sum) $ {Panax Notoginsengf=1; - printf (); the } + return; A } the if(f| | Nowsum>sum)return; + for(intI=1; i<=n;i++) - { $ if(vis[i]==1)Continue; $vis[i]=1; -ans[step]=i; -Getnum (step+1, nowsum+i*a[n-1][step]); thevis[i]=0; - }Wuyi } the - intMain () Wu { -scanf"%d%d",&n,&sum); About Gettri (); $ -memset (Vis,0,sizeof(Vis)); -f=0; -Getnum (0,0); A return 0; +}
1 /*232K 469MS*/2 /*Combination +stl*/ 3#include <iostream>4#include <cstdio>5#include <cstring>6#include <algorithm>7 using namespacestd;8 Const intmaxn=Ten+3;9 intn,sum;Ten intANS[MAXN]; One A intCintNintk) - { - intcresult=1; the for(intI=0; i<k;i++) cresult=cresult* (n-i)/(i+1); - //This cannot be written as cresult=cresult* (n-i)/(k-i), because accuracy can result in errors if the size from large to small may not be divisible - returnCresult; - } + - intMain () + { Ascanf"%d%d",&n,&sum); at for(intI=0; i<n;i++) ans[i]=i+1; - Do - { - intresult=0; - for(intI=0; i<n;i++) Result+=ans[i]*c (n1, i); - if(result==sum) in { - for(intI=0; i<n;i++) cout<<ans[i]<<' '; tocout<<Endl; + Break; - } the} while(Next_permutation (ans,ans+n)); * return 0; $}
"Exhaustion" Poj3187-backward Digit Sums