UVA524 素數環 Prime Ring Problem

題目OJ地址:html

https://www.luogu.org/problemnew/show/UVA524測試

hdu oj 1016:  https://vjudge.net/problem/HDU-1016ui

zoj 1457  :https://vjudge.net/problem/ZOJ-1457spa

題意翻譯

輸入正整數n,把整數1,2,...,n組成一個環,使得相鄰兩個整數之和均爲素數。輸出時,從整數1開始逆時針排列。同一個環剛好輸出一次。..net

多組數據,讀入到EOF結束。翻譯

第i組數據輸出前加上一行Case i:code

相鄰兩組數據中間加上一個空行。orm

Prime Ring Problemhtm

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. blog

Inputn (0 < n < 20). 
OutputThe 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
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<math.h>
 4 int N;
 5 int b[21]={0};
 6 int total=0,a[21]={0};
 7 int search(int);        //回溯過程
 8 int print();            //輸出方案
 9 int pd(int x,int y);    //判斷素數x+y是否質數
10 
11 int main()
12 {
13     int t=0;
14     while(scanf("%d",&N)!=EOF)
15     {
16         a[1]=1;
17         for(int i=2;i<21;i++) a[i]=0;
18         for(int i=0;i<21;i++) b[i]=0;
19         t++;
20         printf("Case %d:\n",t);
21         search(2);
22         printf("\n");
23     }
24     //printf("%d\n",total);                    //輸出總方案數
25 }
26 int search(int t)
27 {
28     int i;
29     for(i=2;i<=N;i++)           //有20個數可選
30      if((!b[i])&&pd(a[t-1],i))  //判斷與前一個數是否構成素數及該數是否可用
31      {
32          a[t]=i;
33          b[i]=1;
34          if (t==N) { if(pd(a[N],a[1])==1) print();}
35          else search(t+1);
36          b[i]=0;
37      }
38 }
39 int print()
40 {
41    int j;
42    total++;
43    //printf("<%d>",total);
44    printf("%d",a[1]);
45    for(j=2;j<=N;j++)
46        printf(" %d",a[j]);
47    printf("\n");
48 }
49 int pd(int x,int y)
50 {
51     int k=2,i=x+y;
52     while(k<=sqrt(i)&&i%k!=0) k++;
53     if(k>sqrt(i)) return 1;
54     else return 0;
55 }

本題目分析見  https://www.cnblogs.com/huashanqingzhu/p/4747009.html

這裏要注意:洛谷OJ的測試數據比較弱,n最大是16.  hdu oj和uva oj原題的n是到20的。

相關文章
相關標籤/搜索