Prime Ring Problem數組
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 74594 Accepted Submission(s): 31690ui
Problem Description.net
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.orm
Note: the number of first circle should always be 1.blog
Inputip
n (0 < n < 20).ci
Outputrem
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.string
You are to write a program that completes above process.it
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
Source
Asia 1996, Shanghai (Mainland China)
題意大體就是說要找到由1~n組成的環,且相鄰的數兩兩相加都要是素數,輸出全部知足條件的序列。
AC代碼以下:
#include<stdio.h>#include<string.h>int f[100]={0};int ans[21],v[21],n;void dfs(int i){ int m; if(i==n&&f[ans[i-1]+ans[0]]==0) //找到8個知足條件的數時輸出 { for(m=0;m<n-1;m++) printf("%d ",ans[m]); printf("%d\n",ans[n-1]); } else { for(m=2;m<=n;m++) //找未用過的數 { if(v[m]==0) //找到尚未用過的數 { if(f[m+ans[i-1]]==0) //若是知足相鄰數和爲素數 { v[m]=-1; //標記已用過 ans[i++]=m; //將m放進數組 dfs(i); //找下一個數 v[m]=0; //接觸標記 i--; //回溯 } } } }}int main(){ int i,j,cases=0; //素數打表 for(i=2;i<100;i++) if(f[i]==0) for(j=i;i*j<100;j++) f[i*j]=1; while(scanf("%d",&n)!=EOF) { cases++; ans[0]=1; printf("Case %d:\n",cases); memset(v,0,sizeof(v)); dfs(1); printf("\n"); } return 0;}--------------------- 做者:yongtaozheng 來源:CSDN 原文:https://blog.csdn.net/Twinkle_sone/article/details/95123292 版權聲明:本文爲博主原創文章,轉載請附上博文連接!