标签:des style io ar os 使用 sp java for
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 28144 Accepted Submission(s): 12533
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
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
题目大意:由1~N的自然数组成一个环,这个环满足相邻的自然数和为素数,
输出所有的情况
思路:本来以为DFS会超时,结果N是小于等于20的,所以直接DFS搜索。DFS
中三个变量,当前数字为now,下一个相邻的数为next,找到N个数中第几个数
为x,如果相邻数相加不是素数,则不必搜下去。否则记录第x个数的结果为next。
如果满足n个数,且最后第N个数与1的和也为素数就输出结果。否则就标记下当前
元素,表示已经使用过,继续找第x+1个数字。最后清除标记。
#include<stdio.h>
#include<string.h>
int num[25],ans[25],vis[25],n;
bool Isprime(int n)
{
int i;
for(i = 2; i < n; i++)
if(n % i == 0)
break;
if(i >= n)
return true;
return false;
}
int dfs(int now,int next,int x)
{
if(!Isprime(n+next))//如果当前的数与将要找的下一个数和不是素数
return 0;
ans[x] = next;
if(x == n && Isprime(next+1))//找到
{
for(int i = 1; i <= n; i++)
if(i!=n)
printf("%d ",ans[i]);
else
printf("%d\n",ans[i]);
return 0;
}
vis[next] = 1;
for(int i = 2; i <= n; i++)
if(vis[i]==0 && dfs(next,i,x+1))
break;
vis[next] = 0;
return 0;
}
int main()
{
int kase = 1;
while(~scanf("%d",&n))
{
memset(ans,0,sizeof(ans));
if(n==1)
{
printf("1\n");
continue;
}
memset(vis,0,sizeof(vis));
for(int i = 1; i <= n; i++)
num[i] = i;
ans[1] = 1;
printf("Case %d:\n",kase++);
for(int i = 2; i <= n; i++)
dfs(1,i,2);
printf("\n");
}
return 0;
}
HDU1016_Prime Ring Problem【DFS】
标签:des style io ar os 使用 sp java for
原文地址:http://blog.csdn.net/lianai911/article/details/41411909