UVa524 - Prime Ring Problem 枚举排列模板题
2015-01-27 19:56
225 查看
题意 给你n,用1~n排列成环,保证相邻两数之和为素数
思路 保证第一个数是1,然后用按序生成排列模板,每次先判断,满足条件否,不满足则剪枝。
注意:(1)两个样例输出间要有空行... 题目没说
(2)如果n为1的时候,我的结果是 1,交上去A了
思路 保证第一个数是1,然后用按序生成排列模板,每次先判断,满足条件否,不满足则剪枝。
注意:(1)两个样例输出间要有空行... 题目没说
(2)如果n为1的时候,我的结果是 1,交上去A了
#include <iostream> #include <cstdio> #include <iostream> #include <algorithm> #include <cstring> using namespace std; const int MAX = 16 + 15 + 1; int a[20]; int notsu[MAX]; int n; void init() { int i,j; for(i=2;i<MAX;i++) { for(j=2;j*j<=i;j++) { if(i % j == 0) { notsu[i] = 1; break; } } } } void out() { for(int i=1;i<=n;i++) { if(i != n) printf("%d ",a[i]); else printf("%d\n",a[i]); } } void dfs(int dep) { if(notsu[a[dep-1] + a[dep-2]]) return; if(dep > n) { if(notsu[a[dep-1]+1]) return; out(); return; } int i,j,tmp; for(i=dep;i<=n;i++) { if(i > dep) { tmp = a[dep]; a[dep] = a[i]; for(j=i-1;j>dep;j--) { a[j+1] = a[j]; } a[dep+1] = tmp; } dfs(dep+1); if(i > dep) { tmp = a[dep]; for(j=dep;j<i;j++) { a[j] = a[j+1]; } a[i] = tmp; } } } int main() { int i,j; init(); int T = 0; while(scanf("%d",&n) == 1 && n) { for(i=1;i<=n;i++) { a[i] = i; } if(T++) puts(""); printf("Case %d:\n",T); dfs(2); } return 0; }
相关文章推荐
- UVA 524 Prime Ring Problem
- UVa 524 Prime Ring Problem【回溯】
- UVa-524 - Prime Ring Problem
- UVa 524 - Prime Ring Problem
- uva 524 - Prime Ring Problem
- 紫书搜索 例题7-4 UVA - 524 Prime Ring Problem
- uva 524 Prime Ring Problem
- Prime Ring Problem(UVA 524)
- UVa-524 - Prime Ring Problem
- UVA524- Prime Ring Problem
- uva 524 prime ring problem——yhx
- UVA524 UVALive5270 HDU1016 ZOJ1457 Prime Ring Problem【DFS】
- 例题7-4 UVA 524 Prime Ring Problem
- UVA 524 Prime Ring Problem
- UVA 524 Prime Ring Problem (暴力预处理)
- UVa 524 Prime Ring Problem (数论&DFS)
- UVA - 524 Prime Ring Problem
- uva 524 prime ring problem——yhx
- Uva524——Prime Ring Problem
- UVa 524 - Prime Ring Problem