题目
Prime Ring Problem
hduoj1016
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
一、题目大意
一个环由n个圆组成,如图所示。将自然数1,2,…,n分别放入每个圆中,相邻两个圆中的数之和应为素数。
注:第一圈的数字应始终为1。
二、代码
题目大致意思就是给你一个数n,要你将从1~n的整数按照相邻相加为素数的方式排成一个圆,将所有的排列方式输出来
我这里用的dfs
代码如下(示例):
#include <stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[20]; //存储结点数据----n个数
int visited[20];//结点是否已搜
int parent[20];//存储结点的前驱 ---本例把它优化成搜索路径上依次是哪些数
int n;
int isprime(int a)
{
for(int i=2;i*i<=a;i++)
{
if(a%i==0) return 0;
}
return 1;
}
void print()
{
for(int i=0;i<n-1;i++)
{
printf("%d ",parent[i]);
}
printf("%d\n",parent[n-1]);
}
void dfs(int v,int count)
{
count++;
if(count==n&&isprime(a[v]+a[0]))
{
parent[count-1]=a[v];
print();
return ;
}
//visited[v]=1;//标记为已搜索
for(int i=0;i<n;i++)
{
if(visited[i]==0&&isprime(a[v]+a[i]))
{
parent[count-1]=a[v];
visited[i]=1;//标记表示已经搜索过
dfs(i,count);
visited[i]=0;//代码运行到这里,说明前面递归进入搜索的路径已经搜完(要么成功,要么失败),接下来要试探下一条路径。因此要把v还原成未搜索状态
}
}
}
int main()
{
int k=0; //记录Case的序号
while( ~scanf("%d",&n) )
{
//初始化图,用并行数组表示图中的n个节点
for(int i=0;i<n;i++)
{
a[i]=i+1; //每个结点存储一个自然数
visited[i]=0; //0表示未搜
parent[i]=-1; //记录前驱结点的序号,-1表示没有前驱 ----优化后是代表第i个数暂时还没有搜到
}
visited[0]=1;
printf("Case %d:\n",(++k));
int count=0;//已经搜索的结点个数
dfs(0,count); //从结点1(数组下标为0)发起深搜, 若搜到一条符合要求的路径,则输出
printf("\n");//Print a blank line after each case
}
return 0;
}