您的位置:首页 > 其它

[HDU 1016]--Prime Ring Problem(回溯)

2015-06-21 19:32 423 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1016

Prime Ring Problem

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


[/b]

[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.

#include <iostream>
#include <cstring>
using namespace std;

#define maxn 40
int vis[21], x[21], T, n;
int prime[maxn] = { 1, 1, 0 };
void init()
{
int i, j;
for (i = 2; i <= maxn; i++){
if (!prime[i]){
for (j = 2; i*j <= maxn; j++)
prime[i*j] = 1;
}
}
}

void dfs(int cur){
if (cur == n&&!prime[1 + x[n - 1]]){
for (int i = 0; i < n; i++){
if (i) cout << ' ';
cout << x[i];
}
cout << endl;
}
else for (int i = 2; i <= n; i++){
if (!vis[i] && !prime[i + x[cur - 1]]){
x[cur] = i;
vis[i] = 1;
dfs(cur + 1);
vis[i] = 0;
}
}
}

int main(){
init();
while (cin >> n){
cout << "Case " << ++T << ':' << endl;
if (n == 1)
cout << 1 << endl;
else if (n & 1)
cout << endl;
else{
memset(vis, 0, sizeof(vis));
x[0] = 1;
dfs(1);
}
cout << endl;//没加这一句pe来个wa,我也是醉了,各种改,无爱了~~~~
}
return 0;
}


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