杭电 1106 Prime Ring Problem

来源:互联网 发布:图片整理软件lr 编辑:程序博客网 时间:2024/05/16 23:05

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 31842    Accepted Submission(s): 14076


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

Source
Asia 1996, Shanghai (Mainland China)
 


别坑了,递归函数里的参数不要偷懒写在全局变量,他的值对后面的结果又影响。


#include<stdio.h>#include<math.h>#include<string.h>#include<stdlib.h>int flag[22]= {0}; //标记i是否用过int c[22]= {0}; //满足条件的排列int prime(int x) { //判断是否质数(40)    if(x==2||x==3||x==5||x==7||x==11||x==13||x==17||x==19||x==23||x==29||x==31||x==37) return 1;    else return 0;}void bfs(int now,int n) {    if(now==n+1&&prime(c[now-1]+1)==1) {     //搜索到最后一项,且最后一项与第一项1相加后任是质数    int p;        for(p=1; p<n; p++) printf("%d ",c[p]);   //打印排列        printf("%d\n",c[p]);        return;    }int i;    for(i=2; i<=n; i++) { //每个数都从2开始找        if(flag[i]==1) continue;  //i是否用过        if(prime(c[now-1]+i)==0) continue; //now的前一项加现在的数 i 不为质数        flag[i]=1;        c[now]=i;        bfs(now+1,n);        flag[i]=0;        c[now]=0;    }}int main() {    int xu;    int cnt=1;    while(scanf("%d",&xu)!=EOF) {        printf("Case %d:\n",cnt++);        memset(flag,0,sizeof(flag));        c[1]=1;  //满足条件排列 第一项为1        flag[1]=1;    //1已用过        bfs(2,xu);        printf("\n");    }}

0 0
原创粉丝点击