Autumn Of Coolerwu 2016-07-09 07:12 采纳率: 100%
浏览 1124
已采纳

HDU 1016一直WA我搞不懂 有会的人吗 求指点

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
代码:
#include
#include
#include
using namespace std;
const int maxn=105;
bool pri[maxn];
int n;
int vis[maxn];
int ans[maxn];
void getPrime()
{
memset(pri,true,sizeof(pri));
for(int i=2;i<=maxn;i++)
{
for(int j=2;j<=sqrt(i);j++)
{
if(i%j==0)
{
pri[i]=false;
break;
}
}
}
pri[0]=pri[1]=false;
}
void dfs(int x)
{
if(x>n)return;
if(x==1)
{
ans[1]=1;
for(int i=2;i<=n;i++)
if(pri[i+1]&&!vis[i])
{
vis[i]=1;
ans[x+1]=i;
dfs(x+1);
vis[i]=0;
}
}
else if(x==n)
{
if(!pri[ans[x]+1])
return;
else
{
printf("%d",ans[1]);
for(int i=2;i<=n;i++)
printf(" %d",ans[i]);
printf("\n");
return;
}
}
else
{
for(int j=2;j<=n;j++)
{
if(pri[j+ans[x]]&&!vis[j])
{
ans[x+1]=j;
vis[j]=1;
dfs(x+1);
vis[j]=0;
}
}
}

}
int main()
{
getPrime();
int k=1;
while(~scanf("%d",&n))
{
if(n<=0||n>=20)break;
memset(vis,0,sizeof(vis));
printf("Case %d:\n",k);
if(n%2!=1)dfs(1);
k++;
printf("\n");
}
return 0;
}

  • 写回答

1条回答 默认 最新

  • devmiao 2016-07-09 14:56
    关注
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里