hdu1016素數環問題
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<20),以1為第一個數,把整數1,2,3,…,n組成一個環,使得相鄰兩個整數的和均為素數。輸出時從整數1開始逆時針排列。同一個環應恰好輸出一次。
輸入、輸出如上所述:
(注意輸出格式,每個Case之間有一行空白)
(還有每一行最後一個數字後是沒有空格的,筆者被坑了兩次,哭了,杭電的OJ評測太嚴格了)
二、問題分析
首先可以生成1~n的全排列,然後逐個判斷是否合法,但排列總數高達19!= 121645100408832000 種,時間複雜度是很高的。
我們可以採用回溯法,利用dfs演算法去求解。在2~n中依次嘗試,用陣列標記哪些數已經使用過,如果沒有被使用且滿足和前一個數的和為素數,就標記已經使用,繼續dfs,直到滿足方案,列印輸出。
由於一個數只用一次,所以兩個數的和最多為2n-1,所以可以先把前40(甚至前37)個數中的素數找出來,組成一個數組,為以後的判斷提供方便。(提示:利用find()函式)。
三、程式碼(附註釋)
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int n, ca = 0; //ca用來列印情況
int a[20], p[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}, vis[20]; //a[]陣列用來存放答案,p[]存放40以內的素數,vis[]陣列用來標記數是否使用過
void dfs(int x)
{
if (x == n && find(p, p + 12, a[0] + a[n-1]) != p + 12) //遞迴邊界,別忘了第一個數和最後一個數的和也為素數
{
for(int i=0;i<n-1;i++)
cout<<a[i]<<" ";
cout<<a[n-1]<<endl; //被坑的地方,注意格式
}
else
for (int i = 2; i <= n; i++) //逐個嘗試2~n的每個數
if (!vis[i] && find(p, p + 12, i+a[x-1]) != p + 12) //如果沒有被使用過且和a[]中前一個之和為素數
{
a[x] = i; //滿足條件,把i加入a[]陣列
vis[i] = 1; //標記已經使用過
dfs(x + 1);
vis[i] = 0; //取消標記
}
}
int main()
{
while (cin>>n && n)
{
memset(a, 0, sizeof(a)); //a[]陣列清零
a[0] = 1; //第一個數為1
memset(vis, 0, sizeof(vis)); //vis[]陣列清零
cout<<"Case "<<++ca<<":"<<endl;
dfs(1); //一定要從1開始dfs(),想想為什麼
cout<<endl;
}
return 0;
}