Fork me on GitHub

题目89:Prime ring problem

时间限制:2 秒

内存限制:128 兆

特殊判题:

提交:54

解决:12

题目描述:

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.


输入:

n (1 < n < 17).

输出:

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.

样例输入:
6
8
样例输出:
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
提示:

 用printf打印输出。




#include<cstdio> #include<cstdlib> #include<cmath> #include<cstring> #include<string> #include<algorithm> #include<iostream> #include<sstream> using namespace std; int prime[10]={3,5,7,11,13,17,19,23,29,31}; int re[17]; bool hash[17];//1~16 bool isprime(int x) { for(int i=0;i<10;i++) if(x==prime[i]) return true; return false; } void dfs(int i,int n) { if(i>2&&!isprime(re[i-1]+re[i-2])) return; if(i<=n) { for(int j=1;j<=n;j++) if(!hash[j]) { hash[j]=true; // if(isprime(re[i-1]+j)) //{ re[i]=j; /* for(int k=1;k<=i;k++) printf("re:%d ",re[k]); printf("\n"); for(k=0;k<=n;k++) if(hash[k]) printf("true "); else printf("false "); printf("\n"); */ dfs(i+1,n); hash[j]=false; //return; // } } } else if(isprime(re[1]+re[n])) { for(i=1;i<n;i++) printf("%d ",re[i]); printf("%d\n",re[i]); return; } } int main() { //freopen("in.txt","r",stdin); int i,j,n,ncase=1; while(scanf("%d",&n)!=EOF) { memset(hash,0,sizeof(hash)); printf("Case %d:\n",ncase++); re[1]=1;hash[1]=true; dfs(2,n); printf("\n"); } return 0; }

 

posted on 2013-01-28 14:48  huashiyiqike  阅读(183)  评论(0编辑  收藏  举报