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

UVa - 524 - Prime Ring Problem

时间:2015-06-25 14:09:29      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:uva   acm   oj   524   prime ring problem   

A ring is composed of n (even number) circles as shown in diagram. Put natural numbers 技术分享 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 <= 16)

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.


You are to write a program that completes above process.

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

回溯法直接搞定,注意判断素数的时候为了提高效率,直接查到小于50的素数手工打表了。。。这个方法在校赛的时候也曾经用过,当时因为超时,直接找了前2000个素数打表。。。

注意:如果最坏情况下的枚举量很大,应该使用回溯法而不是生成-测试法。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <stack>
#include <queue>
#include <bitset> 
#include <cassert> 
#include <cmath>
#include <functional>

using namespace std;

const int maxn = 20;
int n;
int ans[maxn], vis[maxn];
// 小于50的素数:2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 
// 如果i是素数,则ips[i]等于1,否则等于0,这里直接打表搞定。
int isp[50] = { 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, 
				0, 1, 0, 1, 0, 0, 0, 1, 0, 0 };

void dfs(int cur)
{
	// 递归边界,别忘了测试第一个数和最后一个数的和是否是素数
	if (cur == n && isp[ans[0] + ans[n - 1]]) {
		cout << ans[0];
		for (int i = 1; i < n; i++) {
			cout << " " << ans[i];
		}
		cout << endl;
	}
	else for (int i = 2; i <= n; i++) {
		if (!vis[i] && isp[i + ans[cur - 1]]) { // i没有用过,且与前一个数的和是素数
			ans[cur] = i;
			vis[i] = 1;
			dfs(cur + 1);
			vis[i] = 0; // 记得出口处改回来
		}
	}

}

int main()
{
	int kase = 0;
	while (cin >> n) {
		if (kase) {
			cout << endl;
		}
		cout << "Case " << ++kase << ":\n";
		memset(vis, 0, sizeof(vis));
		ans[0] = 1;
		dfs(1);
	}

	return 0;
}




UVa - 524 - Prime Ring Problem

标签:uva   acm   oj   524   prime ring problem   

原文地址:http://blog.csdn.net/zyq522376829/article/details/46635007

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