标签:HDU prim int 1016Prime dfs 素数 circle include
Prime Ring ProblemTime Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1016
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.
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.
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
题目大意是:对于1到n的数求它的所有排列使得每个数与之相邻的数之和为素数(质数)
我们可以先将题目范围的数据判断一下i是否为素数,这里的数据比较小,所以用不着素数筛。然后在dfs排列的时候简单判断一下该数与旁边的相加是否为素数。
if (!v[i] && prim[i+a[k-1]])
因为我们是一个一个的将数放入,所以只需判断与左边的是否满足条件就行了,不需要进行两边判断。具体代码如下
#include <cstdio>
#include <cmath>
#include <cstring>
void dfs(int k);
void print();
int prim[40]= {0};
int n,v[50]= {0},a[20],t=0;
int main() {
for (int i=2; i<=45; i++) {
int j;
for (j=2; j<=sqrt(i); j++)
if (i%j==0) break;
if (j>sqrt(i)) prim[i]=1;
}
while (scanf ("%d",&n)!=EOF) {
t++;
a[1]=1;
v[1]=1;
printf ("Case %d:\n",t);
dfs(2);
printf ("\n");
memset(a,0,sizeof(a));
memset(v,0,sizeof(v));
}
return 0;
}
void dfs(int k) {
if (k==n+1 && prim[a[n]+a[1]]) print();
else {
for (int i=2; i<=n; i++) {
if (!v[i] && prim[i+a[k-1]]) {
a[k]=i;
v[i]=1;
dfs(k+1);
v[i]=0;
a[k]=0;
}
}
}
}
void print() {
for (int i=1; i<n; i++)
printf ("%d ",a[i]);
printf ("%d\n",a[n]);
}
标签:HDU,prim,int,1016Prime,dfs,素数,circle,include 来源: https://blog.51cto.com/u_15249461/2870443
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。