Prime ring Problem
Time Limit: 4000/2000 MS (Java/others) memory limit: 65536/32768 K (Java/Others)
Total submission (s): 20105 accepted submission (s): 9001
Problem descriptiona ring is compose of N circles as shown in digoal. put Natural Number 1, 2 ,..., N into each circle separately, and the sum of numbers in two adjacent circles shoshould be a prime.
Note: The number of First Circle shoshould always be 1.
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 abve 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
Sourceasia 1996, Shanghai (Mainland China)
Recommend
Jgshining
Question: prime ring (Classic search)
Code:
Statement 1:
# Include <cstdio> # include <iostream> # include <cstring> using namespace STD; int Yes [22]; bool in [22]; bool prim [50]; int N; void primtable () {int I, j; memset (Prim, 0, sizeof (prim); for (I = 3; I <= 50; I ++) {for (j = 2; j <= I-1; j ++) {if (I % J = 0) prim [I] = true ;}}} void DFS (int pos) {int I, U; If (Pos> N) {int M = Yes [1] + Yes [N]; if (prim [m] = false) {for (I = 1; I <= N; I ++) printf ("% d % C", yes [I], I = n? '\ N': ''); // printf (" \ n "); // here PE once} return;} for (I = 2; I <= N; I ++) {u = I + Yes [pos-1]; If (prim [u] = false & in [I] = false) {Yes [POS] = I; In [I] = true; DFS (Pos + 1); In [I] = false ;}} int main () {int CAS = 1; primtable (); While (scanf ("% d", & N )! = EOF) {memset (in, 0, sizeof (in); Yes [1] = 1; in [1] = true; printf ("case % d: \ n ", CAS ++); DFS (2); printf (" \ n ");} return 0;} // 203 Ms
|
8765975 |
2013-07-30 16:19:31 |
Accepted |
1016 |
203 Ms |
228 K |
1125 B |
C ++ |
Statement 2:
#include<cstdio>#include<iostream>#include<cstring>using namespace std;int yes[22];bool in[22];bool prim[50];int n;void no_prim(){ int tmp,i,j; for(i=3;i<20;i+=2) { if(prim[i]==false) { tmp=i<<1; for(j=i*i;j<50;j+=tmp) prim[j]=true; } }}void dfs(int pos){ int i,u; if(pos>n) { int m=yes[1]+yes[n]; if(prim[m]==false&&m%2||m==2) { for(i=1;i<=n;i++) printf("%d%c",yes[i],i==n?'\n':' '); //printf("\n"); } return; } for(i=2;i<=n;i++) { u=i+yes[pos-1]; if((!prim[u]&&u%2||u==2)&&in[i]==false) { yes[pos]=i; in[i]=true; dfs(pos+1); in[i]=false; } }}int main(){ no_prim(); int cas=1; while(scanf("%d",&n)!=EOF) { memset(in,0,sizeof(in)); yes[1]=1; in[1]=true; printf("Case %d:\n",cas++); dfs(2); printf("\n"); } return 0;}// 234MS
|
8765965 |
2013-07-30 16:18:52 |
Accepted |
1016 |
234 Ms |
228 K |
1143 B |
C ++ |