HDU 1016 Prime Ring Problem (DFS)
2016-05-28 11:53
453 查看
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 41149 Accepted Submission(s): 18218
[align=left]Problem Description[/align]
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.
[align=left]Input[/align]
n (0 < n < 20).
[align=left]Output[/align]
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.
[align=left]Sample Input[/align]
6
8
[align=left]Sample Output[/align]
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
[align=left]Source[/align]
Asia 1996, Shanghai (Mainland China)
题解:输入n ,从1开始,把n(1~n)的数围成一个环,要使每两个相邻的数加起来都是素数。
dfs撸一波。。。
AC代码:
#include<iostream> #include<cstdlib> #include<cstdio> #include<cstring> #include<cmath> #include<string> #include<cstdlib> #include<iomanip> #include<vector> #include<list> #include<map> #include<queue> #include<algorithm> using namespace std; int a[30],b[30]; int n,cas=0; int prime(int x) { int i; for(i=2;i*i<=x;i++) if(x%i==0)return 0; return 1; } void dfs(int x,int y) { for(int i=1;i<=n;i++) { if(b[i]==0) { if(prime(x+i)==1) { b[i]=1; //标志i用过 a[y]=i; //储存 i 的值 dfs(i,y+1); //继续搜 b[i]=0; //没有搜到就标志当前的 i 没用过 } } } if(y==n+1) //n+1个是结束标志 { if(prime(x+1)==1) //判断最后一个和第一个,即 1 相加是否成立 { for(int i=1;i<n;i++) printf("%d ",a[i]); printf("%d\n",a ); } } } int main() { while(cin>>n) { printf("Case %d:\n",++cas); a[1]=1; b[1]=1; dfs(1,2); printf("\n"); } return 0; }
相关文章推荐
- Handler与Message
- redis消息发送与订阅
- gulp的使用
- tcpdump permission denied问题解决
- 框架模式 MVC 在Android中的使用
- 初学 android databinding
- 编程错误集
- Android开发技术问题收集
- HDU 1754 I Hate It 伸展树
- 深入浅出SQL Server中的死锁
- php-fpm配置文件
- git的使用和Eclipse配置和使用Egit
- Hadoop Serialize (一)
- POJ 2299 Ultra-QuickSort (树状数组 + 离散化)
- linux 下启动关闭mysql服务的命令 以及 mysql中文乱码
- 写算法程序时非常容易犯的思维定势错误积累
- Git push 失败原因总结
- Android进阶专题五:NDK JNI变量和方法调用
- 关于#ifdef __cplusplus extern
- 用C++的 new 代替 C 的 malloc 进行内存分配