杭电oj 1016 Prime Ring Problem

Prime Ring Problem

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

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.

杭电oj 1016  Prime Ring Problem

 
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~n的数围成一个圈,但是每相邻的两个数的和必须为素数。

   下面是代码:
 #include <iostream>
#include <cmath>
using namespace std;
#define MAX 22
int a[MAX]; //标记数组
int b[MAX];
int n;
bool prime(double n)
{
int i, m;
m = (int)sqrt(n);
for (i=; i<=m; i++)
if ((int)n%i == )
return false;
return true;
}
void dfs(int i)
{
int j;
if (i>=n)
{
if (prime(double(b[n-]+))) //判断最后一个和第一个数的和是不是素数
{
cout<<b[];
for (j=; j<n; j++)
cout<<" "<<b[j];
cout<<endl;
}
}
else
{
for (j=; j<=n; j++)
{
if (a[j] || !prime(double(b[i-]+j))) //a[j]已经被加入到圈中或者相邻两个数和不是素数,则continue
continue;
a[j] = ; //如果j已经加入圈中,则标记为1
b[i] = j;
dfs(i+);
a[j] = ;
}
}
}
int main()
{
int i=, j;
while (cin>>n)
{
memset(a,,sizeof(a)); //全置为0
cout<<"Case "<<i++<<":"<<endl;
b[] = ;
dfs();
cout<<endl;
}
return ;
}
 
 
上一篇:为网站添加favicon.ico图标


下一篇:68.纯 CSS 创作一本色卡