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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)