Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 30395 Accepted Submission(s): 13525
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.

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.
You are to write a program that completes above process.
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | //第一次写dfs,既然发现和小白上的代码一样,开心 #include<cstdio> #include<cstring> #include<algorithm> using namespace std; int prime[]= {0,0,1,1,0,1,0,1,0,0,0, 1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0, 0,0,1,0,1,0,0,0,0,0,1,0,0,0 }; //方便判断一个数是否素数 int flag[25]; //标志数组 int c[25]; //结果数组 int n; void dfs( int cur) { int i,j; if (cur==n+1&&prime[1+c[cur-1]]) //别忘记第一个数和最后一个数的和也应该是素数 { for (j=1; j<n; j++) printf ( "%d " ,c[j]); printf ( "%d\n" ,c[n]); } else for (i=2; i<=n; i++) //每个数都应是从2——n选择 if (!flag[i]&&prime[i+c[cur-1]]) //是否满足条件 { c[cur]=i; //尝试把i作为第cur个满足条件的数 flag[i]=1; //设置使用标志 dfs(cur+1); flag[i]=0; //谨记清除标记 } } int main() { int k=1; while (~ scanf ( "%d" ,&n)) { printf ( "Case %d:\n" ,k++); memset (flag,0, sizeof (flag)); c[1]=1; dfs(2); //第一个数就是1,从第二个数开始 printf ( "\n" ); } } 不知什么鬼,G++提交超时,c++ 256ms |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧