nyoj 素数环 DFS

题目链接:http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=488

此题关键是剪枝,如输入奇数时不成立。

另通过此题学习,发现求素数时查表比调用求素数的函数快很多。

AC代码:

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
int ans[25],visited[25],n,count=0,flag;
int prime[40]={0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0};
bool p_n(int m)
{
	for(int i=m-1;i>=2;i--)
	{
		if(m%i==0)
		{
			return false;
		}
	}
	return true;
}
void dfs(int pos)
{
	//显示ans[]和visited[] 
	{
	//	cout<<"visited[]:"<<endl;
	//	for(int i=1;i<=n;i++)
	//	{
	//		cout<<visited[i]<<" ";
	//	}
	//	cout<<endl;
	//	cout<<"ans[]:"<<endl;
	//	for(int i=1;i<=n;i++)
	//	{
	//		cout<<ans[i]<<" ";
	//	}
	//	cout<<endl<<"----------------------------------------------------------"<<endl;
	}
	if(pos>n+1)
	{
		return ;
	}
	if(pos==n+1)
	{
		if(ans[n]!=0)
		{
		//	printf("%d",ans[1]);
			for(int i=1;i<=n;i++)
			{
				printf("%d ",ans[i]);
			}
			printf("\n");
		}
	}
	else
	{
		if(pos!=n)
		{
			//cout<<"first i:"<<i<<"     pos:"<<pos<<endl;
			for(int i=2;i<=n;i++)
			{
		//		cout<<"second i:"<<i<<"     pos:"<<pos<<endl;
				if(visited[i]==0)
				{
		//			cout<<"third i:"<<i<<"     pos:"<<pos<<endl;
					if(prime[(ans[pos-1]+i)])//上一个位置加上i是素数 
					{
		//				cout<<"fourth :i"<<i<<"     pos:"<<pos<<endl;
						visited[i]=1;//i被使用 
						ans[pos]=i;//当前位置值为i 
						dfs(pos+1);//搜索下一位置的值 
				//		cout<<"i:"<<i<<"     pos:"<<pos<<endl; 
	//显示ans[]和visited[]					
	{
	//	cout<<"visited[]:"<<endl;
	//	for(int j=1;j<=n;j++)
	//	{
	//		cout<<visited[j]<<" ";
	//	}
	//	cout<<endl;
	//	cout<<"ans[]:"<<endl;
	//	for(int j=1;j<=n;j++)
	//	{
	//		cout<<ans[j]<<" ";
	//	}
	//	cout<<endl;
	}
						ans[pos]=0;
						visited[i]=0;
					}
				}			
			}	
		}
		else
		{
			for(int j=2;j<=n;j++)
			{
				if(visited[j]==0&&prime[(j+1)]&&prime[(j+ans[n-1])])
				{
					flag=1;
					visited[j]=1;
					ans[pos]=j;
					dfs(n+1);
					ans[pos]=0;
					visited[j]=0;
				}
			}
		}
	}
}
int main()
{
	while(~scanf("%d",&n))
	{
		count++;
		if(n==0)
		{
			break;
		}
		memset(visited,0,sizeof(visited));
		memset(ans,0,sizeof(ans));
		ans[1]=1,visited[1]=1,flag=0;
		printf("Case %d:\n",count);
		if(n==1)
		{
			flag=1;
			printf("%d\n",1);
			continue;
		}
		if(n%2==0)
		{
			dfs(2);
		}
		if(flag==0)
		{
			printf("No Answer\n");
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值