UVA 524

时间:2023-03-08 20:24:07

Description

UVA 524

A ring is composed of n (even number) circles as shown in diagram. Put natural numbers UVA 524 into each circle separately, and the sum of numbers in two adjacent circles should be a prime.

UVA 524

Note: the number of first circle should always be 1.

Input

n (0 < n <= 16)

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.

You are to write a program that completes above process.

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

解题思路:如果这题用暴力枚举的话排列总数最高可高达16!=2*10^13,。就会超时。

所以这用回溯。用一个数组来储存要输出的序列,判断条件就是如果目前的数加上他前面的数的和为素数并且没有这数没被标记。满足条件就加1递归并标记。直到走到递归边界(cur==n)。

代码如下:

 #include<cstdio>
#include<cstring>
using namespace std;
int vis[],isp[],A[],n;
int is_prime(int x) //用一个函数来判断是不是素数
{
for (int i = ; i*i<= x ; i++)
if (x% i == ) return ;
return ;
} void dfs(int cur)
{
if(cur==n&&isp[A[]+A[n-]])  //判断到递归边界没有,并且不要忘了判断最后一个和第一个加起来是不是素数,因为它是一个圆。
{
for(int i=; i<n-; i++)
printf("%d ", A[i]);//按照题目格式输出,注意空格问题。(我TM栽在这一上午)
printf("%d",A[n-]);
printf("\n");
}
else
for(int i=; i<=n; i++) //从2开始一个一个放
if(!vis[i]&&isp[i+A[cur-]]) //如果满足条件,和没有被标记
{
A[cur]=i;
vis[i]=; //标记
dfs(cur+);  //递归
vis[i]=; //清除标记
}
}
int main()
{
int m=;
while(scanf("%d",&n)==&&n)
{
if(m>)
printf("\n");
++m;
for(int i=; i<=n*; i++)
isp[i]=is_prime(i);
printf("Case %d:\n",m);
 //memset(vis,,sizeof(vis));
A[]=; //A[0]一定为1
dfs();    //从一开始递归
}
return ;
}