Prime Ring Problem
2014-02-23 17:20
155 查看
Problem Description
A ring is compose of n circles as shown in diagram. Put natural number 1, 2, ..., n 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 < 20).
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. Print solutions in lexicographical order.
You are to write a program that completes above process.
Print a blank line after each case.
Sample Input
Sample Output
思路:典型的深搜题,思想看代码
虽然题很水,但还是做了很长时间,这就是菜鸟的世界,你不懂。。。。。。
A ring is compose of n circles as shown in diagram. Put natural number 1, 2, ..., n 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 < 20).
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. Print solutions in lexicographical order.
You are to write a program that completes above process.
Print a blank line after each case.
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
思路:典型的深搜题,思想看代码
#include<stdio.h> #include<string.h> using namespace std; int a[20],vis[20],n; int prime(int m) { int i; for(i=2;i*i<=m;i++) if(m%i==0) return 0; return 1; }//判断素数函数 int dsf(int step) { int i; if(step==n+1&&prime(a +a[1]))//递归结束的条件,不要忘记判断最后一个数和第一个数的和是否是素数 { for(i=1;i<n;i++) printf("%d ",a[i]); printf("%d\n",a ); return 0; } for(i=2;i<=n;i++)//题目要求从一开始,所以这里从二开始循环 { if(!vis[i]&&prime(i+a[step-1]))//判断当前的数是否被用过,并且与上一个数的和是素数 { a[step]=i; vis[i]=1;//每用一次就标记上 dsf(step+1);调用递归函数 vis[i]=0;回溯的时候清零,以便下次用 } } } int main() { int k=1; a[1]=1; while(scanf("%d",&n)!=EOF) { memset(vis,0,sizeof(vis));标记数组清零 printf("Case %d:\n",k++); dsf(2);从二开始 printf("\n"); } return 0; }
虽然题很水,但还是做了很长时间,这就是菜鸟的世界,你不懂。。。。。。
相关文章推荐
- HDOJ 1016 Prime Ring Problem 简单搜索
- acm P1016 Prime Ring Problem(DFS深搜)
- Hdu 1016 Prime Ring Problem
- HDU-1016 Prime Ring Problem [DFS]
- HDU 1016 Prime Ring Problem
- HDU_1016 Prime Ring Problem 素数环
- ACM HDU 1016 Prime Ring Problem
- HDU 1016 Prime Ring Problem
- HDU 1016 Prime Ring Problem (DFS)
- hdu 1016 Prime Ring Problem 搜索
- UVA-542 Prime Ring Problem
- HDOJ 1016 Prime Ring Problem(深搜)
- Prime Ring Problem(DFS)
- Prime Ring Problem
- 【dfs】hdu 1016 Prime Ring Problem
- HDU 1016 Prime Ring Problem(DFS回溯+素数判断)
- HDU 1016 Prime Ring Problem(经典DFS+回溯)
- 题目1459:Prime ring problem(素数环问题)
- hdu1016 Prime Ring Problem
- UVa 524 - Prime Ring Problem