2012年9月19日 星期三

uva 524 - Prime Ring Problem



  Prime Ring Problem 

A ring is composed of n (even number) circles as shown in diagram. Put natural numbers $1, 2, \dots, 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 <= 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



Miguel A. Revilla
1999-01-11

DFS
#include<stdio.h>
#include<cstring>
#include<string>
#include<vector>
#define REP(i, b, n) for (int i = b; i < n; i++)
#define rep(i, n) REP(i, 0, n)
#define DBG 0
using namespace std;

int cases=1,N;
vector<int>res;
bool notp[50];
bool trav[16];
void getP(){
notp[0]=notp[1]=1;
REP(i,2,50){
if(!notp[i]){
if(DBG)printf("p %d\n",i);
for(int j=i*i;j<50;j+=i)notp[j]=1;
}
}
}
void print(){
bool ll=0;
rep(i,res.size()){if(ll)printf(" ");ll=1,printf("%d",res[i]);}printf("\n");
}
void DFS(int cur,int len){
if(DBG)printf("len %d\n",len);
if(len==N){if(DBG)printf("len %d: cur first %d %d\n",len,cur+1,res[0]);
if(!notp[cur+1+res[0]])print();}
else{
trav[cur]=1;
rep(i,N)
if(!trav[i]&&!notp[cur+1+(i+1)]){
if(DBG)printf("%d + %d is prime\n",cur+1,i+1);
res.push_back(i+1);
DFS(i,len+1);
res.pop_back();
}
trav[cur]=0;
}
}
void ans(){
res.clear(),res.push_back(1);
printf("Case %d:\n",cases++);
DFS(0,1);
}
int main(){
bool ll=0;
getP();
while(scanf("%d",&N)==1){
if(ll)printf("\n");ll=1;
ans();
}
}

沒有留言:

張貼留言