回溯法解决素数环问题

#include <iostream>
#include <math.h>
using namespace std;

#define N 100000
int isp[2 * N];
int a[N];
int visited[N];

int is_prime(int n)
{
	int i;
	int flag = 0;
	for (i = 2; i <= (int)sqrt(n) + 1;i++)
	{
		if (n%i == 0)
		{
			return 0;
		}
	}
	return 1;
}

//素数环问题
void dfs(int n, int cur)
{
	if (cur == n && isp[a[cur - 1] + a[0]])
	{
		for (int i = 0; i < n; i++)
		{
			cout << a[i] << " ";
		}
		cout << endl;
	}
	else for (int i = 1; i <= n; i++)
	{
		if (!visited[i] && (i==1 || isp[i + a[cur - 1]]))
		{
			a[cur] = i;
			visited[i] = 1;
			dfs(n, cur + 1);
			visited[i] = 0;
		}
	}
}

int main()
{
	int n;
	cin >> n;
	for (int i = 2; i <= 2 * n; i++)
		isp[i] = is_prime(i);
	dfs(n, 0);
	return 0;
}

    原文作者:回溯法
    原文地址: https://blog.csdn.net/barry283049/article/details/42407097
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞