Uva524

Prime Ring Problem UVA - 524

A ring is composed of n (even number) circles as shown in diagram. Put natural numbers 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 ≤ 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

 1 #include 
 2 #include 
 3 #include 
 4 #include 
 5 #include<string.h>
 6 #include
 7 #include
 8 #define LL long long
 9 #define maxn 1005
10 using namespace std;
11 int n,ans,tot;
12 int a[20],check[100];
13 bool vis[20];
14 int isprime(int x)
15 {
16     for(int i=2;i*i<=x;i++)
17         if(x%i==0)return 0;
18             return 1;
19 }
20 void dfs(int cur)
21 {
22     if(cur==n+1&&check[a[1]+a[n]])
23     {
24         for(int i=1;i<=n;i++)
25             {
26                 if(i!=1)
27                 printf(" %d",a[i]);
28             else
29                 printf("%d",a[i]);
30             }
31         printf("\n");
32         return;
33     }
34     for(int i=2;i<=n;i++)
35     {
36        if(!vis[i]&&check[i+a[cur-1]])
37        {
38            a[cur]=i;
39            vis[i]=1;
40            dfs(cur+1);
41            vis[i]=0;
42        }
43     }
44 }
45 
46 int main()
47 {
48     ans=1;
49     while(~scanf("%d",&n))
50     {
51         if(ans>1)printf("\n");
52         memset(vis,0,sizeof vis);
53         for(int i=2;i<=2*n;i++)
54             check[i]=isprime(i);
55         a[1]=1;//题目要求从1开始逆时针排列
56         vis[1]=1;
57         printf("Case %d:\n",ans++);
58         dfs(2);
59         //printf("\n");这样写的话会PE,原因是在最后一次输出时会多空一行
60     }
61     return 0;
62 }

 

转载于:https://www.cnblogs.com/zuiaimiusi/p/10888029.html

你可能感兴趣的:(Uva524)