hdu 1016Prime Ring Problem

来源:互联网 发布:拷贝文件夹到mac 编辑:程序博客网 时间:2024/06/06 09:42
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
68
 

Sample Output
Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2
给你N个圈让你填数字,第一个圈永远都要是1,让相邻的两个数之和为素数。把所有的情况都打出来。
#include<stdio.h>#include<string.h>int a[21],book[21];int z[41]= {0,1,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0};//最大的数是20,素数打到40就行int n;void dfs(int x) {    int k,j;    if(x==n && z[a[1]+a[x]]) {//数字是否填完,与第一个数相加是否是素数,        for(j=1; j<n; j++)            printf("%d ",a[j]);        printf("%d\n",a[n]);        return ;    }    else {        for(k=2; k<=n; k++) {            if(z[a[x]+k]&& book[k]==0) {                a[x+1]=k;                book[k]=1;//因为每个数只能用一次                dfs(x+1);                book[k]=0;//回溯撤销            }     }    }}int main() {    int m=0;    while(scanf("%d",&n)!=EOF) {        printf("Case %d:\n",++m);        memset(book,0,sizeof(book));        a[1]=1;        dfs(1);        printf("\n");    }    return 0;}
0 0