UVA524-Prime Ring Problem(搜索剪枝)

时间:2022-03-28 05:17:07

Problem UVA524-Prime Ring Problem

Accept:6782  Submit:43814

Time Limit: 3000 mSec

UVA524-Prime Ring Problem(搜索剪枝) Problem Description

A ring is composed of n (even number) circles as shown in diagram. Put natural numbers 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.

UVA524-Prime Ring Problem(搜索剪枝) Input

n (0 < n ≤ 16)

UVA524-Prime Ring Problem(搜索剪枝) 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.

UVA524-Prime Ring Problem(搜索剪枝) Sample Input

6
8
 

UVA524-Prime Ring Problem(搜索剪枝) Sample Ouput

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 <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std; const int maxn = ,maxp = ;
bool vis[maxn];
int n,ans[maxn]; bool is_prime[maxp];
int prime[maxp]; void Euler(){
memset(is_prime,true,sizeof(is_prime));
int cnt = ;
is_prime[] = is_prime[] = false;
for(int i =;i < maxp;i++){
if(is_prime[i]) prime[cnt++] = i;
for(int j = ;j<cnt && prime[j]<=maxp/i;j++){
is_prime[i*prime[j]] = false;
if(i%prime[j] == ) break;
}
}
} void dfs(int cur,int *ans){
if(cur==n && is_prime[ans[n-]+ans[]]){
for(int i = ;i < n;i++){
if(i != ) printf(" ");
printf("%d",ans[i]);
}
printf("\n");
return;
}
for(int i = ;i <= n;i++){
if(!vis[i] && is_prime[ans[cur-]+i]){
vis[i] = true;
ans[cur] = i;
dfs(cur+,ans);
vis[i] = false;
}
}
} int main()
{
//freopen("input.txt","r",stdin);
int iCase = ;
Euler();
while(~scanf("%d",&n)){
if(iCase > ) printf("\n");
memset(vis,false,sizeof(vis));
ans[] = ;
vis[] = true;
printf("Case %d:\n",iCase++);
dfs(,ans);
}
return ;
}