Title Description:
Enter a positive integer n, the integer 1,2...n to form a ring, so that the adjacent two numbers and is a prime number. The output is arranged counterclockwise from the integer 1 and cannot be duplicated;
Sample input:
6
Sample output:
1 4 3 2 5 6
1 6 5 2 3 4
Method 1: (Generate test method, time Out)
#include <bits/stdc++.h>
#define MAXN 100
using namespace Std;
int ISP[MAXN], A[MAXN];
void Get_prime (void)//***** prime number playing table
{
memset (ISP, 1, sizeof (ISP));
isp[0]=isp[1]=0;
for (int i=2; i<maxn; i++)
{
if (Isp[i])
{
for (int j=2; j*i<maxn; j + +)
{
isp[i*j]=0;
}
}
}
}
int main (void)
{
Std::ios::sync_with_stdio (False), Cin.tie (0), Cout.tie (0);
Get_prime ();
int n;
CIN >> N;
for (int i=0; i<n; i++)
{
a[i]=i+1;
}
Do
{
int flag=1;
for (int i=0; i<n; i++)//**** Try one by one
{
if (!isp[a[i]+a[(i+1)%n])//**** judging legality
{
flag=0;
Break
}
}
if (flag)//**** The output sequence if valid
{
for (int i=0; i<n; i++)
{
cout << A[i] << "";
}
cout << Endl;
}
}while (Next_permutation (a+1, a+n)); The position of 1 is unchanged
return 0;
}
Method 2: (dfs+ backtracking)
Code:
#include <bits/stdc++.h>
#define MAXN 100
using namespace Std;
int ISP[MAXN], A[MAXN], VIS[MAXN], N;
void Get_prime (void)//**** prime number playing table
{
memset (ISP, 1, sizeof (ISP));
isp[0]=isp[1]=0;
for (int i=2; i<maxn; i++)
{
if (Isp[i])
{
for (int j=2; i*j<maxn; i++)
{
isp[i*j]=0;
}
}
}
}
void dfs (int cur)
{
if (cur==n && isp[a[0]+a[cur-1])//**** recursive boundary
{
for (int i=0; i<n; i++)//*** Print legal sequence
cout << A[i] << "";
cout << Endl;
}
Else
{
for (int i=0; i<n; i++)//*** Try one by one
{
if (!vis[i]&&isp[i+a[cur-1]])//***i not used and meet the conditions
{
A[cur]=i; Stores the current sequence
Vis[i]=1; Mark
DFS (CUR+1); Recursive
vis[i]=0; Remove marks
}
}
}
}
int main (void)
{
Std::ios::sync_with_stdio (False), Cin.fie (0), cout.fie (0);
Get_prime ();
CIN >> N;
memset (Vis, 0, sizeof (VIS));
DFS (0);
return 0;
}
Prime ring (dfs+ backtracking)