1. 程式人生 > >hdu 1016 Prime Ring Problem(dfs,素數環)

hdu 1016 Prime Ring Problem(dfs,素數環)

Prime Ring Problem Time Limit:2000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

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

題目大意:

給出一個數 n  ,用 1 - n  組成一個環,這個換的要求是,從 1 開始,並且每兩個相鄰的數的和都為素數

分析:

這就是典型的素數環,劉汝佳《演算法競賽入門經典》 上有講解,我在這就不多說了,

每次選一個數,判斷這個數和前一個數的和是否為 素數,如果是進行下一個數,否則換數,如果這個數 是第 n 個數,那麼需要判斷是否與第一個數的和也為素數。這裡面判斷素數的時候不能夠每次都用判斷素數的方法判斷一遍,那樣會超時,用一個數組直接事先打一個素數表就行了

附上程式碼:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <algorithm>
#include <map> 
using namespace std;

/*
 *   篩選法素數打表 
 */
const int MAXN = 100;
bool is_prime[MAXN];
void init()
{
	memset(is_prime,true,sizeof(is_prime));
	is_prime[0] = is_prime[1] = false;
	for(int i = 2;i < MAXN;i++)
	{
		if(is_prime[i])
		{
			for(int j = i * i;j < MAXN;j+=i)
			{
				is_prime[j] = false;
			}
		}
	}
}

int visit[100];
int n;

void DFS(int t,int ans[])
{
	if(t > n)
	return;
	if(t == n && is_prime[ans[n - 1] + ans[0]])
	{
		for(int i = 0;i < n;i++)
		{
			if(i != 0)
			printf(" ");
			printf("%d",ans[i]);
		}
		printf("\n");
	}
	for(int i = 1;i <= n;i++)
	{
		if(!visit[i] && is_prime[ans[t - 1] + i])
		{
			ans[t] = i;
			visit[i] = 1;
			DFS(t + 1,ans);
			visit[i] = 0;
			ans[t] = 0;
		}
	}
}

int main()
{
	init();
	int flag = 1;
	while(cin >> n)
	{
		printf("Case %d:\n",flag++);
		memset(visit,0,sizeof(visit));
		int ans[100] = {0};
		ans[0] = 1;
		visit[1] = 1;
		DFS(1,ans);
		printf("\n");
	}
	return 0;
}