码迷,mamicode.com
首页 > 其他好文 > 详细

素数环(简单搜索)

时间:2015-11-11 13:11:38      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:

 

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 36338    Accepted Submission(s): 16024


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
 
 
其中n如果是除1的奇数的话就不存在素数环,在测试数据含有大量奇数时加以判断可节省时间
 
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 using namespace std;
 5 int a[50],b[21],test[21];
 6 int n;
 7 void prime()
 8 {
 9     int i,j;
10     for(i=2;i<=50;i++)
11     {
12         for(j=2;j<=i/2;j++)
13             if(i%j==0)
14                 break;
15         if(j==(i/2+1))
16             a[i]=1;
17         else
18             a[i]=0;
19     }
20 }
21 void dfs(int s)
22 {
23     int i,j,k;
24     if(s==n+1&&a[b[n]+1])
25     {
26         for(i=1;i<n;i++)
27             cout<<b[i]<<" ";
28         cout<<b[n]<<endl;
29     }
30     else for(i=2;i<=n;i++)
31         if(a[b[s-1]+i]&&!test[i])
32         {
33             b[s]=i;
34             test[i]=1;
35             dfs(s+1);
36             test[i]=0;
37         }
38 }
39 int main()
40 {
41     b[1]=1;
42     prime();
43     int i,j;
44     while(cin>>n&&n)
45     {
46         cout<<"Case "<<j<<":"<<endl;
47         memset(test,0,sizeof(test));
48         dfs(2);
49         cout<<endl;
50         j++;
51     }
52 }

 

素数环(简单搜索)

标签:

原文地址:http://www.cnblogs.com/a1225234/p/4955547.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!