UVa - 524 - Prime Ring Problem

A ring is composed of n (even number) circles as shown in diagram. Put natural numbers $1, 2, \dots, 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 <= 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;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值