标签:des style color os io for ar art
Description
3 1 2 4 4 3 6 7 9 16Behind 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.
Input
Output
Sample Input
4 16
Sample Output
3 1 2 4
强大的STL,我比赛的时候是DFS做的。
题意:1~n排列操作的值为sum.
next_permutation的用法:按字典序输出全排列,没有返回false。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<limits.h> typedef long long LL; using namespace std; int a[15],f[15]; int n,sum; int solve() { int s=0; for(int i=0;i<n;i++) s+=f[i]*a[i]; return s; } int main() { while(~scanf("%d%d",&n,&sum)) { for(int i=0;i<n;i++) a[i]=i+1; memset(f,0,sizeof(f)); f[0]=1; for(int i=1;i<n;i++) { for(int j=i;j>=1;j--) f[j]+=f[j-1];//杨辉三角 } while(solve()!=sum) next_permutation(a,a+n); for(int i=0;i<n;i++) printf(i==n-1?"%d\n":"%d ",a[i]); } return 0; }DFS版:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<limits.h> #include<cmath> typedef long long LL; using namespace std; int num[15],a[15]; int visit[15],p[15]; int n,sum,flag; int solve(int k) { for(int i=1;i<=n;i++) p[i]=num[i]; while(k>1) { for(int i=1;i<k;i++) p[i]=p[i]+p[i+1]; k--; } return p[1]; } void dfs(int k,int s) { if(s==n+1) { if(solve(n)==sum) { for(int i=1;i<=n;i++) printf(i==n?"%d\n":"%d ",num[i]); flag=1; return ; } } if(flag) return ; for(int i=1;i<=n;i++) { if(!visit[i]) { visit[i]=1; num[s]=a[i]; dfs(i,s+1); visit[i]=0; } } } int main() { while(~scanf("%d%d",&n,&sum)) { for(int i=1;i<=n;i++) a[i]=i; memset(visit,0,sizeof(visit)); memset(num,0,sizeof(num)); flag=0; dfs(1,1); } return 0; }
POJ 1146:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<limits.h> typedef long long LL; using namespace std; int main() { int len; char s[51]; while(scanf("%s",s)!=EOF) { if(s[0]=='#') break; len=strlen(s); if(next_permutation(s,s+len)) printf("%s\n",s); else printf("No Successor\n"); } return 0; }
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<limits.h> typedef long long LL; using namespace std; char str[220]; int main() { while(~scanf("%s",str)) { int len=strlen(str); sort(str,str+len); do{ printf("%s\n",str); }while(next_permutation(str,str+len)); } return 0; }
POJ 3187 Backward Digit Sums(next_permutation),布布扣,bubuko.com
POJ 3187 Backward Digit Sums(next_permutation)
标签:des style color os io for ar art
原文地址:http://blog.csdn.net/u013582254/article/details/38701383