[CF45G]Prime Problem

题目大意:将$1$到$n(1<n\leqslant6000)$分成若干组数,要求每组数的和均为质数,若存在一种分配方式,输出每个数所在的组的编号,有多组解输出任意一组解,若不存在,输出$-1$

题解:根据这一题的结论分[CF735D]Taxes

卡点:未判断奇数分成$3$个质数的情况

 

C++ Code:

#include <cstdio>
#define maxn 6010
int n;
int bel[maxn], idx;
inline bool isp(int x) {
	for (int i = 2; i * i <= x; i++) {
		if (x % i == 0) return false;
	}
	return true; 
}
void solve(int x) {
	if (isp(x)) {
		idx++;
		for (int i = n; i; i--) {
			if (x >= i && !bel[i]) {
				bel[i] = idx;
				x -= i;
			}
		}
		return ;
	}
	if (x & 1) {
		if (isp(x - 2)) solve(2), solve(x - 2);
		else solve(3), solve(x - 3);
		return ;
	}
	for (int i = x + 1 >> 1; i > 1; i--) if (isp(i) && isp(x - i)) {
		solve(i), solve(x - i);
		return ;
	}
	
}
int main() {
	scanf("%d", &n);
	solve(n * (n + 1) >> 1);
	for (int i = 1; i <= n; i++) {
		printf("%d", bel[i]);
		putchar(i == n ? '\n' : ' ');
	} 
	return 0;
}

  

posted @ 2018-10-24 15:29  Memory_of_winter  阅读(195)  评论(0编辑  收藏  举报