UVA - 524 Prime Ring Problem (经典回溯问题)
2014-08-11 10:46
387 查看
Prime Ring Problem |
into each circle separately, and the sum of numbers in two adjacent circles should be a prime.
Note: the number of first circle should always be 1.
Input
n (0 < n <= 16)Output
The output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements.You are to write a program that completes above process.
Sample Input
6 8
Sample Output
Case 1: 1 4 3 2 5 6 1 6 5 2 3 4 Case 2: 1 2 3 8 5 6 7 4 1 2 5 8 3 4 7 6 1 4 7 6 5 8 3 2 1 6 7 4 3 8 5 2
题目大意:输入正整数n,把1,2,3,……n组成一个环,使得相邻的两个整数之和均为素数。输出时从整数1开始逆时针排列,同一个换恰好输出一次。n<=16
解析:本来我是想用全排列,筛选出素数环的,但是无奈,时间效率比较低。于是参考了刘汝佳的题解敲了一遍,加深了对于回溯的认识。
#include <stdio.h> #include <math.h> #include <string.h> #include <algorithm> using namespace std; const int N = 50; int isp ; int A ; int vis ; int n; int is_prime(int n) { for(int i = 2; i <= sqrt(n); i++) { if( n % i == 0) { return 0; } } return n; } void dfs(int cur) { if(cur == n && isp[A[0] + A[n-1]]) { //递归边界 for(int i = 0; i < n; i++) { printf("%d", A[i]); if( i != n-1) { printf(" "); } } printf("\n"); }else { for(int i = 2; i <= n; i++) { if( !vis[i] && isp[i+A[cur-1]] ) { //如果i没有用过,并且与前一个数之和为素数 A[cur] = i; vis[i] = 1; dfs(cur+1); vis[i] = 0; } } } } int main() { int cas = 0; isp[0] = 0; isp[1] = 0; for(int i = 2; i < N; i++) { isp[i] = is_prime(i); } while( scanf("%d",&n) != EOF) { memset(vis,0,sizeof(vis)); if(cas++) { printf("\n"); } for(int i = 0; i < n; i++) { A[i] = i+1; } printf("Case %d:\n",cas); dfs(1); } return 0; }
相关文章推荐
- UVa 524 - Prime Ring Problem(回溯)
- Prime Ring Problem UVA - 524 回溯
- UVa 524 Prime Ring Problem(DFS , 回溯)
- 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(回溯)
- 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
- UVA - 524 Prime Ring Problem
- UVA524- Prime Ring Problem
- UVa524 - Prime Ring Problem 枚举排列模板题
- uva 524 Prime Ring Problem
- UVa-524 - Prime Ring Problem
- UVa - 524 - Prime Ring Problem