您的位置:首页 > 其它

hdu 1016 Prime Ring Problem(dfs)

2014-12-09 15:29 330 查看

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 28391 Accepted Submission(s): 12644


[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<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n;
int vis[50];
int seq[50];
int prime[100];
bool okp(int x)
{
int i;
for(i=2;i<=sqrt(x);i++)
{
if(x%i==0) break;
}
if(i>sqrt(x)) return true;
return false;
}
void prim()
{
memset(prime,0,sizeof(prime));
int i;
for(i=2;i<=50;i++)
{
if(prime[i]==0)
{
if(okp(i))
prime[i]=1;
}
int k=i,tc=2;
while(k*tc<=50)
{
prime[k*tc]=2;
tc++;
}
}
}
void dfs(int x)
{
int i;
if(x>n) return ;
if(x==n&&prime[seq[x]+1]==1)
{
for(i=1;i<=n;i++)
{
printf("%d",seq[i]);
printf("%c",i==n?'\n':' ');
}
}
else
{
for(i=2;i<=n;i++)
{
if(vis[i]==0&&prime[seq[x]+i]==1)
{
vis[i]=1;
seq[x+1]=i;
dfs(x+1);
vis[i]=0;
}
}
}
}
int main()
{
int cas=1,i,j;
prim();//筛法求素数
while(scanf("%d",&n)!=EOF)
{
printf("Case %d:\n",cas++);
//if(n==1) continue;  //测试数据中不会出现n==1
memset(vis,0,sizeof(vis));
seq[1]=1;
vis[1]=1;
dfs(1);
printf("\n");
}
return 0;
}


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