# 【HDU】1016 DFS——Prime Ring Problem

Problem 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

AC代码：

//
//  main.cpp
//  1016
//
//  Created by showlo on 2018/4/15.
//

#include <stdio.h>
#include <math.h>
#include <algorithm>
using namespace std;

int a[25],vis[25];
int n,num;

int isPrime(int n){
int flag=0;
int i;
for (i=2; i<n; i++) {
if (n%i==0)
flag=1;
}
if (flag==1)
return 0;
return 1;
}

int dfs(int k)
{
int i,flag=0;
if (k==n+1&&isPrime(a[n]+a[1])) {
printf("%d",a[1]);
for (i=2; i<=n; i++) {
printf(" %d",a[i]);
}
printf("\n");
return 0;
}
else {
for (i=2; i<=n; i++) {
flag=1;
a[k]=i;
if (vis[i]==1||isPrime(a[k]+a[k-1])==0) {
flag=0;
continue;
}
if (flag) {
vis[i]=1;
dfs(k+1);
vis[i]=0;
}
}
}
return num;
}
int main() {
int ans;
num=1;
while (scanf("%d",&n)!=EOF) {
memset(vis, 0, sizeof(vis));
memset(a, 0, sizeof(a));
printf("Case %d:\n",num);
a[1]=1;
dfs(2);
num++;
printf("\n");
}
return 0;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：【HDU】1016 DFS——Prime Ring Problem 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)