您的位置:首页 > 其它

Prime Ring Problem—hdu1016(DFS)

2016-05-06 14:27 344 查看

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 40339 Accepted Submission(s): 17813

[align=left]Problem Description[/align]
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.



[align=left]Input[/align]
n (0 < n < 20).

[align=left]Output[/align]
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.

[align=left]Sample Input[/align]

6
8


[align=left]Sample Output[/align]

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,将每个数都遍历一边,找出符合的情况;

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<string>
#include<algorithm>
#include<queue>
using namespace std;
int n;
int a[25];//保存结果
int flag[25];//记录一个数是否已用过
bool isprime(int n)
{
if (n == 1 || n == 0)
return 0;
if (n == 2)
return 1;
for (int i = 2; i <= sqrt((double)n); i++)
{
if (n%i == 0)
return 0;
}
return 1;
}
void dfs(int tot)
{
if (tot == n-1)
{
if (isprime(a[n - 1] + a[0]))
{

int o = 0;
for (int i = 0; i < n; i++)
{
while (o++)
{
printf(" ");
break;
}
printf("%d", a[i]);
}
printf("\n");
}
return;
}
for (int i = 2; i <= n; i++)
{
if (flag[i] == 0)
{
if (isprime(a[tot] + i))
{
flag[i] = 1;
a[tot + 1] = i;
dfs(tot + 1);
flag[i] = 0;
}
}
}
}
int main()
{
int k = 1;
while (~scanf("%d", &n))
{
printf("Case %d:\n", k++);

a[0] = 1;
memset(flag, 0, sizeof(flag));
dfs(0);
printf("\n");
}
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: