HDU1016 DFS+回溯(保存路径)

时间:2023-03-09 21:42:38
HDU1016  DFS+回溯(保存路径)

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 55053    Accepted Submission(s):
24366

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.

HDU1016  DFS+回溯(保存路径)

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 ... n   n个数排序 1必须在第一位 两个数相加要为素数(1与最后一个数相加也必须为素数) 输出所有满足上述的序列。
解析 我们先1~n分别求出与它相加为素数的数存进数组,然后就相当于建了一个图 从1出发 一层一层向下推 基础DFS 然后在回溯一下 记录路径就好了
AC代码
 #include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <string>
#include <queue>
#include <vector>
using namespace std;
const int maxn= ;
const int maxm= 1e4+;
const int inf = 0x3f3f3f3f;
typedef long long ll;
int visit[maxn],order[maxn];
vector<int> v[maxn];
int n,cnt;
int isPrime(int num )
{
int tmp =sqrt( num);
for(int i= ;i <=tmp; i++)
if(num %i== )
return ;
return ;
}
void dfs(int x)
{
visit[x]=; //标记访问过
order[cnt++]=x; //记录路径
for(int i=;i<v[x].size();i++) //df搜边
{
if(visit[v[x][i]]==)
{
dfs(v[x][i]);
}
}
visit[x]=; //回溯
if(cnt==n&&isPrime(x+)) //长度为n且最后一个数与1相加为素数
{
for(int i=;i<cnt;i++)
{
if(i==cnt-)
printf("%d\n",order[i]);
else
printf("%d ",order[i]);
}
}
cnt--;
}
int main()
{
int kase=;
while(scanf("%d",&n)!=EOF)
{
for(int i=;i<=n;i++)
v[i].clear();
for(int i=;i<=n;i++)
{
for(int j=;j<=n;j++)
{
if(isPrime(i+j)==&&i!=j) //保存能够与i相加为素数的数
v[i].push_back(j);
}
}
// for(int i=1;i<=n;i++)
// {
// cout<<i;
// for(int j=0;j<v[i].size();j++)
// printf(" %d",v[i][j]);
// cout<<endl;
// }
memset(visit,,sizeof(visit)); //初始化访问数组 0未访问过
printf("Case %d:\n",kase++);
cnt=; //路径长度初始化
dfs();
printf("\n");
}
}