2020 BIT冬训-图&&DFS&&BFS C - Prime Ring Problem HDU - 1016
Problem Description
火火某天AK太多了心烦,想带领小伙伴们做游戏 。
游戏内容如下:
当火火喊出一个数字n时,便有n个小伙伴,身上带着1到n的数字,手牵手拉成一个环。当环里的每个人相邻两人身上数字之和都为素数时,便找到了一个环。当找出所有的环时,游戏便结束。
Note: 每个环的第一个数字必须是1
Input
n (0 < n < 20).
Output
输出格式如下方输出样例所示。(注意case)
每行一串数字表示一种环中数字的排列顺序。数字的顺序必须满足:从1开始,顺时针或逆时针。按字典序输出所有解决方案。您将编写一个完成上述过程,帮助大家顺利完成游戏的程序。
别忘了在每组方案后面输出一个空行。
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
对于每个位子从2到n进行DFS即可。
注意有多组数据,且每组数据的每种情况后不能跟空格否则会pe。
AC代码如下:
#include<cstdio> #include<cstring> #include<queue> #include<algorithm> using namespace std; int n,cnt,id,isp[205],p[205],vis[105],ans[105]; void dfs(int x){ if(cnt==n) if(isp[x+1]){ ans[cnt-1]=x; printf("%d",ans[0]); for(int i=1;i<cnt;i++) printf(" %d",ans[i]); printf("\n"); return; } for(int i=2;i<=n;i++){ if(!vis[i]&&isp[x+i]){ vis[i]=1; ans[cnt++]=i; dfs(i); cnt--; vis[i]=0; } } } void find_prime(){//isp存储下标是否是素数,是则为1,否则为0 memset(isp,1,sizeof(isp)); isp[1]=0; for(int i=2;i<=200;i++){ if(isp[i]) p[cnt++]=i; for(int j=0;j<cnt&&p[j]*i<=200;j++){ isp[i*p[j]]=0; if(i%p[j]==0) break; } } } int main(){ find_prime(); while(~scanf("%d",&n)){ cnt=1; ans[0]=1; printf("Case %d:\n",++id); dfs(1); printf("\n"); } return 0; }

浙公网安备 33010602011771号