HDU 1016Prime Ring Problem【深搜】

View Code
#include<stdio.h>
#include<string.h>
int prime[40];
int a[20];
int vis[20];
int n;
int isprime(int n)
{
int i;
for(i=2;i*i<=n;i++)
if(n%i==0)
return 0;
return 1;
}
void dfs(int cur)
{
int i;
if(cur==n&&prime[a[0]+a[n-1]]) //递归边界,最后一个数和第一个数和是质数
{
for(i=0;i<n;i++)
printf("%d%c",a[i],(i==n-1)?'\n':' ');
}
else
for(i=2;i<=n;i++) //尝试放置每个数 i
if(!vis[i]&&prime[i+a[cur-1]]) //如果 i 没有用过,并且与前一个数的和为质数
{
a[cur]=i;
vis[i]=1; //标记
dfs(cur+1);
vis[i]=0; //清除标记
}
}
int main()
{
int i,k=0;
memset(prime,0,sizeof(prime));
memset(vis,0,sizeof(vis));
prime[2]=1;
for(i=3;i<40;i+=2)
if(isprime(i))
prime[i]=1;
while(scanf("%d",&n)!=EOF)
{
k++;
printf("Case %d:\n",k);
for(i=0;i<n;i++)
a[i]=i+1;
dfs(1);
putchar('\n');
}
return 0;
}

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
总结: 回溯算法
 
posted @ 2012-03-15 12:49  'wind  阅读(131)  评论(0编辑  收藏  举报