Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 14314 Accepted Submission(s): 6524
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.

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.
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
今年暑假的时候看到羽哥a的~~果断跟题
典型的dfs深度搜索,数据量就是从1-20开始~~搜索的范围很小
直接进行递归搜索:
post code:
#include<stdio.h>
#include<string.h>
int record[25];
int used[25];
int n;
int prime[100];
void dfs(int num,int sum) //num记录的是当前搜索的点,sum记录的是已经搜索到了几个点满足相邻两数之和为质数
{
int i;
if(sum==n){ if( prime[num+1]==0 )return; //判断最后一个点和第一个点相连是否也为质数
for(i=1;i<=n;i++)
{
printf("%d",record[i]); //record 记录的点的位置。
if(i!=n)printf(" ");
else printf("\n");
}
return ;
}
for(i=2;i<=n;i++) //从1往后的所有的点都开始遍历。
{
if( used[i]==0 && prime[i+num]==1 ) //判断这个点是被遍历过了,并且里两数相加是否为质数
{
used[i]=1; //遍历过后将此点标记
record[sum+1]=i; //记录此点的位置
dfs( i,sum+1 ); //进行下一次搜索
used[i]=0; //将此点的位置恢复成未标记。
}
}
}
int main()
{
int i,j,ji=0;
for(i=2;i<=99;i++) //寻找2-99的全部质数
prime[i]=1;
for(i=2;i*i<=99;i++)
{
if(prime[i]==1){
for(j=i+i;j<99;j+=i)
prime[j]=0;
}
}
while( scanf("%d",&n)!=EOF )
{
ji++;
memset( record, 0, sizeof(record) ); //两个数组全部初始化为0
memset( used , 0, sizeof(used) );
printf("Case %d:\n",ji);
record[1]=1; //数组第一个的值为1.
used[1]=1;
dfs(1,1); //dfs从1开始进行搜索
printf("\n");
}
}
本文介绍如何使用深度搜索算法解决环形排列问题,确保相邻元素之和为质数,通过实例展示算法实现过程。
394

被折叠的 条评论
为什么被折叠?



