Prime Ring Problem HDU - 1016 (dfs)

时间:2025-02-01 12:03:20

Prime Ring Problem

HDU - 1016

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.

Prime Ring Problem HDU - 1016 (dfs) 

Inputn (0 < n < 20). 
OutputThe 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
 #include<iostream>
#include<stdio.h>
#include<cstring>
#include<queue> using namespace std; int n;
int a[];
int vis[];
bool mark[]; void init() // 素数筛
{
for(int i = ; i < ; ++i)
mark[i] = true; for(int i = ; i < ; ++i)
{
if(mark[i] == true)
{
for(int j = i*i; j < ; j += i)
{
mark[j] = false;
}
}
}
} // 边枚举边判断,不要最后一次性判断,会超时
void dfs(int step)
{
if(step > )
{
if(mark[a[step-]+a[step-]] == false) // 判断最后两个数
return;
} if(step == n+)
{
if(mark[a[n]+a[]] == false) // 判断最后一个数与第一个数
return;
for(int i = ; i < n; ++i)
printf("%d ", a[i]);
printf("%d\n", a[n]); } for(int i = ; i <= n; ++i)
{
if(!vis[i])
{
a[step] = i;
vis[i] = ;
dfs(step+);
vis[i] = ;
} }
} int main()
{
init();
int cas = ;
a[] = ;
while(scanf("%d", &n) != EOF)
{
printf("Case %d:\n", cas++);
memset(vis, , sizeof(vis));
dfs();
printf("\n");
} return ;
}