prime ring problem

H | prime ring problem 质数环问题

prime ring problem

题目分析
dfs递归搜索直到s=n时停止;停止时判断头和尾相加是否为素数;
这道题特别容易PE。。。
1.每一行末尾不能有空格
2.每一个case中间空行且第一个case前不能空行

代码

#include<iostream>
#include<string.h>
using namespace std;
int book[20],a[20];
int n,z=1;
int zhishu(int k)
{
		for (int i = 2; i < k; i++)
			if (k % i == 0)return 0;
		return 1;
}
void dfs(int s)
{
	if (s == n && zhishu(a[n] + 1))
	{
		for (int j = 1; j < n; j++)
			cout << a[j]<<" ";
		cout << a[n] << endl;
	}
	else
	{
		for (int p = 2; p <= n; p++)
			if (zhishu(a[s] + p) && book[p] != 1)
			{
				a[s + 1] = p;
				book[p] = 1;
				dfs(s + 1);
				book[p] = 0;
			}
	}
}
int main()
{
	while (cin >> n)
	{
		if (z >= 2)
			cout << endl;
		memset(a, 0, sizeof(a));
		memset(book, 0, sizeof(book));
		a[1] = 1;
		cout << "Case " << z <<":" << endl;
		dfs(1);
		z++;
	}
	return 0;
}
上一篇:X-Y问题(X-Y problem)


下一篇:给初学Qt者的小TIP