您的位置:首页 > 其它

uva 524 回溯法

2015-08-10 21:26 357 查看
#include <bits/stdc++.h>
using namespace std;
int kase, n;
const int prim[] = {1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37};
int ans[17];
bool vis[17];
bool is_primf(int x)
{
	for (int i = 0; i < 13; i++)
		if (x == prim[i]) return 1;
	return 0;
}
void dfs(int cur, int now)
{
	vis[cur] = 1;
	ans[now] = cur;
	if (now == n && is_primf(cur + ans[1]))
	{
		for (int i = 1; i <= n; i++)
			cout << ans[i] << (i == n ? "\n" : " ");
	}
	else for (int i = 1; i <= n; i++)
			if (!vis[i] && is_primf(i + cur))
				dfs(i, now + 1), vis[i] = 0;

}
int main(int argc, char const *argv[])
{
	#ifndef ONLINE_JUDGE
	freopen("1.txt", "r", stdin);
	freopen("2.txt", "w", stdout);
	#endif
	int first = 1;
	while (cin >> n)
	{
		if (!first) cout << endl;
		else first = 0;//末尾不用换行!!!!!!!!!!!!
		cout << "Case " << ++kase << ":" << endl;
		memset(vis, 0, sizeof(vis));
		memset(ans, 0, sizeof(ans));
		dfs(1, 1);
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: