题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1016
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K
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
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#define Maxn 40
using namespace std;
int prime[Maxn],n;
int a[21],vis[21];
int Is_prime(int x)
{
//判断是不是素数
for(int i=2;i<x;i++)
{
if(x%i==0)
return 0;
}
return 1;
}
void Type()
{
//素数打表
for(int i=1;i<Maxn;i++)
{
if(Is_prime(i))//判断是不是素数
prime[i]=1;
}
}
void Print(int k)
{
//输出数组a
for(int i=1;i<k;i++)
{
if(i!=k-1)
printf("%d ",a[i]);
else
printf("%d\n",a[i]);
}
}
void dfs(int x,int k)
{
//x用来表示递归次数(就是符合条件的次数),k用来计数以便往数值a里面填值
if(x==n&&prime[1+a[x]])
{
//判断是不是到了最后一个数 && 最后一个数和第一个数的和是素数
Print(k);
return ;
}
for(int i=2;i<=n;i++)
{
if(!vis[i]&&prime[i+a[x]])
{
vis[i]=1;
a[k]=i; //往数组里填数
dfs(x+1,k+1);
vis[i]=0; //回溯
}
}
}
int main()
{
Type();
int t=0;
while(~scanf("%d",&n))
{
memset(a,0,sizeof(a));
memset(vis,0,sizeof(vis));
a[1]=1;vis[1]=1;t++;
printf("Case %d:\n",t);
dfs(1,2);
printf("\n");
}
return 0;
}