首页 > 其他 > 详细

HDU 1016 Prime Ring Problem

时间:2015-08-28 19:11:35      阅读:156      评论:0      收藏:0      [点我收藏+]

Prime Ring Problem

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


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
 

 

Source
 

 

Recommend
JGShining
 
  相对简单的一道题,dfs深搜。即在N个数的全排列,找出符合提议的素数组。
    注意:一边排列 一边检查
#include<stdio.h>
#include<math.h>
int num;
bool use[20];
int CP[20];
bool isprime(int a)
{
	for(int i=2;i<=sqrt(a+0.0);i++)
	{
		if(a%i==0)
			return false;
	}
	return true;

}
void dfs(int n)
{

	if(n==num&&isprime(1+CP[n-1]))
	{
		for(int i=0;i<num;i++)
		{
			printf(i==num-1?"%d\n":"%d ",CP[i]);
		}
	}
	else
	{
		for(int i=2;i<=num;i++)
		{
			if(!use[i]&&isprime(i+CP[n-1]))
			{
				CP[n]=i;
				use[i]=true;
				dfs(n+1);
				use[i]=false;
			}
		}
	}
}
void init()
{
	for(int i=1;i<=num;i++)
	{
		use[i]=false;
	}
	CP[0]=1;
	use[1]=true;
}
int main()
{
	int time=0;
	while(scanf("%d",&num)!=EOF)
	{
		init();
		printf("Case %d:\n",++time);
		dfs(1);
		puts("");	
	}

}

  

HDU 1016 Prime Ring Problem

原文:http://www.cnblogs.com/WillsCheng/p/DFS.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!