您的位置:首页 > 其它

HDU 1016 Prime Ring Problem(素数环)

2016-07-22 16:22 369 查看
题目:

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是偶数的时候才有解,所以实际上n只是2到18这9个偶数而已。

如果追求效率的话,可以硬编码9个字符串,换行的问题还要注意一下。

因为后来提交之后没有出现超时,所以就没有这么做。

既然n最多18,那么2个数的和最多也就35,不超过35的素数只有10个,所以本题的素数判断也是硬编码的。

注意:如果在递归的函数(例如这里的place函数)里面使用嵌套的循环,一定要搞清楚continue和break的作用对象是哪个循环。

代码:

#include<iostream>
using namespace std;

int list[19];//最多18个数,list[0]不使用
int n;

bool ok(int a, int b)
{
int c = a + b;
if (c == 3 || c == 5 || c == 7 || c == 11 || c == 13 || c == 17 || c == 19 || c == 23 || c == 29 || c == 31)return true;
return false;
}

void place(int deep)
{
if (deep > n)
{
if (ok(1, list[n]))
{
for (int i = 1; i <= n; i++)
{
cout << list[i];
if (i < n)cout << " ";
}
cout << endl;
}
return;
}
for (int i = 2; i <= n; i++)
{
bool flag = false;
for (int j = 1; j < deep; j++)
{
if (list[j] == i)
{
flag = true;
break;
}
}
if (flag)continue;
if (!ok(list[deep - 1], i))continue;
list[deep] = i;
place(deep + 1);
}
}

int main()
{
int cas = 1;
list[1] = 1;
while (cin >> n)
{
cout << "Case " << cas << ":" << endl;
if (n % 2 == 0)place(2);
cout << endl;
cas++;
}
return 0;
}

这个题目我出现了几次格式错误,主要是行尾多了一个空格。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: