码迷,mamicode.com
首页 > 其他好文 > 详细

hdoj 1016 Prime Ring Problem 【DFS】

时间:2014-07-30 14:57:03      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:深搜

策略如题

链接 http://acm.hdu.edu.cn/showproblem.php?pid=1016

代码:

#include<stdio.h>
#include<string.h>
int prime[25] = {1, 1}, n, vis[25]; //vis作用:标记是否用过
int a[25];
void f()  //找出来前20的素数 判定为0
{
	for(int i = 2; i <= 24; i ++){
		if(prime[i] == 0)
		for(int j = i+i; j <= 24; j +=i)
		prime[j] = 1;
	}
}
void dfs(int step)
{
	int i;
	if(step == n){
		if(prime[a[step-1]+a[step-2]]==0&&prime[a[step-1]+1] == 0){  //这处就是判断最后一位能不能和邻接的两个环能否构成素数
			printf("1");
			for(int j = 1; j < n; j ++)
			printf(" %d", a[j]);
			printf("\n");
		}
		return ;
	}
	for(i = 2; i <= n; i ++){
		if(vis[i] == 0&&prime[i+a[step-1]] == 0){  //如果i没有被用并且满足跟前面一位的构成素数,就将其存到相应的数组中
			a[step] = i;
			vis[i] = 1;
			dfs(step+1);
			vis[i] = 0;
		}
		
	}
}
int main(){
	f();
	int v = 1;
	while(scanf("%d", &n) == 1){
		memset(vis, 0, sizeof(vis));
		printf("Case %d:\n", v++);
		a[0] = 1;
		vis[1] = 1;
		dfs(1);
		printf("\n");
	}
	return 0;
}


hdoj 1016 Prime Ring Problem 【DFS】,布布扣,bubuko.com

hdoj 1016 Prime Ring Problem 【DFS】

标签:深搜

原文地址:http://blog.csdn.net/shengweisong/article/details/38296969

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!