1. 程式人生 > >HDU 1016 Prime Ring Problem(素數環)

HDU 1016 Prime Ring 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是偶數的時候才有解,所以實際上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; }
這個題目我出現了幾次格式錯誤,主要是行尾多了一個空格。