输入正整数n,把整数1,2,3,...,n组成一个环,使得相邻两个整数和为素数,输出时从整数1开始逆时针排列。同一个环只输出一次,n <= 16
样例输入:
6
样例输出:
1 4 3 2 5 6
1 6 5 2 3 4
回溯法
#include <stdio.h>
#include <iostream>
#include <math.h>
using namespace std;
const int maxn = 20;
int a[maxn];
bool vis[maxn];
bool isPrame(int n)
{
for (int i = 2; i <= sqrt(n); ++i)
{
if (!(n % i))
return false;
}
return true;
}
void work(int n, int cur)
{
if (cur > n)
{
if (isPrame(a[1] + a[n]))
{
for (int i = 1; i <= n; ++i)
printf("%d ", a[i]);
printf("\n");
}
}
else
{
for (int i = 1; i <= n; ++i)
if (!vis[i])
{
a[cur] = i;
if (isPrame(a[cur] + a[cur - 1]))
{
vis[i] = 1;
work(n, cur + 1);
vis[i] = 0;
}
}
}
}
int main()
{
int n;
scanf("%d", &n);
a[1] = 1;
vis[1] = 1;
work(n, 2);
return 0;
}