站外(回溯题)
  • 板块题目总版
  • 楼主_Mix_
  • 当前回复0
  • 已保存回复0
  • 发布时间2023/12/27 20:23
  • 上次更新2023/12/27 23:17:43
查看原帖
站外(回溯题)
923194
_Mix_楼主2023/12/27 20:23

RT:

素数环:将1到20这20个数摆成一个环,要求相邻个两个数的和是素数。

#include<bits/stdc++.h>
using namespace std;
bool b[21]={0};
int tot=0,a[21]={0};
int search(int);//回溯过程
int print();//输出方案
bool pd(int,int);/判断素数
int main()
{
	search(1);
	cout<<tot<<endl;//输出总方案数
}
int search(int t)
{
	int i;
	for(i=1;i<=20;i++)//有20个数可选
	if(pd(a[t-1],i)&&(!b[i]))//判断与前一个数是否构成素数及该数是否可用
	{
		a[t]=i;
		b[i]=1;
		if(t==20)
		{
			if(pd(a[20],a[1]))
			print();
		}
		else
		search(t+1);
		b[i]=0;
	}
}
void print()
{
	tot++;
	cout<<tot<<" ";
	for(int j=1;j<=20;j++)
	cout<<a[j]<<" ";
	cout<<endl;
}
bool pd(int x,int y)
{
	int k=2,i=x+y;
	while (k<=sqrt(i)&&i%k!=0)
	k++;
	if(k>sqrt(i))
	return 1;
	else
	return 0;
}
2023/12/27 20:23
加载中...