Description
A ring is composed of n (even number) circles as shown in diagram. Put natural numbers $1, 2,……, 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 <= 16)
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.
You are to write a program that completes above process.
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<=16的素數環,簡單的枚舉會超時,用回溯法
代碼實現
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define MAXN 50
using namespace std;
int n, A[MAXN] = {1}, ispe[MAXN], vis[MAXN];
void dfs(int cur) //dfs回溯
{
if(cur == n&& ispe[A[0] + A[n - 1]])
{
int k;
for(int i = 1; i < n; i++)//輸出語句的控制
{
printf("%d ", A[i-1]);
k=i;//最後一個i存儲在k中
}
printf("%d",A[k]);
printf("\n");
}
else for(int i = 2; i <= n; i++)
{
if(!vis[i]&& ispe[i + A[cur - 1]])
{
A[cur] = i;
vis[i] = 1; //對其進行標記
dfs(cur + 1);
vis[i] = 0; //清除標記
}
}
}
int main()
{
for(int i = 2; i <= 50; i++)
ispe[i] = 1;
for(int i = 2; i <= 50; i++)
for(int j = i + i; j + i <= 50; j += i)
ispe[j] = 0;
int kase = 0;
while(cin >> n)
{
if(kase++)
printf("\n");
printf("Case %d:\n", kase);
dfs(1);
}
return 0;
}