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

Prime Ring Problem—hdu1016(DFS)

时间:2016-05-07 09:52:34      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 40339    Accepted Submission(s): 17813


Problem Description
A ring is compose of n circles as shown in diagram. Put natural number 1, 2, ..., n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.

Note: the number of first circle should always be 1.

技术分享
 

Input
n (0 < n < 20).
 

Output
The output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. Print solutions in lexicographical order.

You are to write a program that completes above process.

Print a blank line after each case.
 

Sample Input
6 8
 

Sample Output
Case 1: 1 4 3 2 5 6 1 6 5 2 3 4 Case 2: 1 2 3 8 5 6 7 4 1 2 5 8 3 4 7 6 1 4 7 6 5 8 3 2 1 6 7 4 3 8 5 2
 
___________________________________________________________________________________________________________________________

题目的意思是讲1到n的每个数构成一个环,相邻两个数之和为素数,将符合的结果按字典序全部输出;
方法采用的是DFS,将每个数都遍历一边,找出符合的情况;


#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<string>
#include<algorithm>
#include<queue>
using namespace std;
int n;
int a[25];//保存结果
int flag[25];//记录一个数是否已用过
bool isprime(int n)
{
	if (n == 1 || n == 0)
		return 0;
	if (n == 2)
		return 1;
	for (int i = 2; i <= sqrt((double)n); i++)
	{
		if (n%i == 0)
			return 0;
	}
	return 1;
}
void dfs(int tot)
{
	if (tot == n-1)
	{
		if (isprime(a[n - 1] + a[0]))
		{
			
			int o = 0;
			for (int i = 0; i < n; i++)
			{
				while (o++)
				{
					printf(" ");
					break;
				}
				printf("%d", a[i]);
			}
			printf("\n");
		}
		return;
	}
	for (int i = 2; i <= n; i++)
	{
		if (flag[i] == 0)
		{
			if (isprime(a[tot] + i))
			{
				flag[i] = 1;
				a[tot + 1] = i;
				dfs(tot + 1);
				flag[i] = 0;
			}
		}
	}
}
int main()
{
	int k = 1;
	while (~scanf("%d", &n))
	{	
		printf("Case %d:\n", k++);
		
		a[0] = 1;
		memset(flag, 0, sizeof(flag));
		dfs(0);
		printf("\n");
	}
	return 0;

}


Prime Ring Problem—hdu1016(DFS)

标签:

原文地址:http://blog.csdn.net/jelly_acm/article/details/51331381

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