题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1016点击打开链接
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 49670 Accepted Submission(s): 21903
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
题意:就是给你一个整数n(0 < n < 20)表示从1到n这n个数,让你把它们排在在一个环上,使得不论是从顺时针还是逆时针相邻的两个数之和都为素数,让你打表输出
所有的可能顺序。
思路:首先由于看到这个n很小,所以暗示我们可以用暴力搜索的方法找到每一种情况;第一步,把1到n标记为0,表示它们还没有加入这个素数环中;
第二步,由于每一个环的起始位数都为1,故从1开始每次遍历所有的数,看它能不能接到此时的这个数后面(即这两个数加起来为素数),如果可以则,则标记这个数为1(表示
已用过),继续向下深搜,直到所有数的用完为止,这时判断,环上的数的个数是不是n,且环的第一个元素与最后一个元素之和为素数(这个没判断过,之前判断的是最后一个与
倒数第二个元素和是不是为素数),如果是则按要求格式输出,(如果不是,则向上回溯到环上的数个数为n-1,之前加入的第n个数的标记更新为0,这是重点与核心!!
发现还是找不到满足题意的情况,继续回溯—深搜—回溯,直到找到满足情况的顺序为止)。
#include<iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
using namespace std;
int n;
int vis[25];
int is_prime[45];
int ans[25];
void prime()//通过埃氏筛法,找出40以内的素数
{
int i, m;
memset(is_prime, 0, sizeof(is_prime));
m = sqrt(40 + 0.5);
is_prime[1] = 1;
for(i = 2; i <= m; i++)
{
if(!is_prime[i])
{
for(int j = i * i; j <= 40; j += i)
{
is_prime[j] = 1;
}
}
}
return;
}
void dfs(int p)
{
if(p == n && is_prime[ans[0] + ans[n - 1]]== 0) //递归的终止条件,第一个与最后一个之和为素数一定要判断
{
cout << ans[0];
for(int i = 1; i < n; i++)
{
printf(" %d", ans[i]);
}
cout << endl;
return;
}
else
{
for(int i = 2; i <= n; i++) //一个一个的找可以接到当前数后面的数
{
if(!vis[i] && is_prime[i + ans[p - 1]] == 0)
{
vis[i] = 1;; //找到的这个数标记为1,避免下次重复找,和防止死循环!!
ans[p] = i; //这个数接到当前数后面
dfs(p + 1); //递归去找这个数后面的数
vis[i] = 0; //核心!!!
}
}
}
return;
}
int main()
{
int cnt = 0;
ans[0] = 1;
prime();
while(~scanf("%d", &n))
{
memset(vis, 0, sizeof(vis));
cout << "Case " << ++cnt << ":" << endl;
dfs(1);
cout << endl;
}
return 0;
}