洛谷P1036 选数

P1036

DFS+素数判断

一道简单的dfs题,数据规模也不大,可以直接用普通版素数判断法。
注意dfs去重时采取升序的方法。

话不多说,直接干代码:

#define  _CRT_SECURE_NO_WARNINGS
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define LL long long
#define ULL unsigned long long
#define INF 0x3f3f3f3f
#define LNF = 0x3f3f3f3f3f3f3f3f;
using namespace std;
const int maxn = 1002;
int n, k, ans, arr[maxn];

int read() {
	int x = 0, f = 1; char c = getchar();
	while (!isdigit(c)) { if (c == '-') f *= -1; c = getchar(); }
	while (isdigit(c)) { x = x * 10 + c - '0'; c = getchar(); }
	return x * f;
}

void put(int x) {
	if (x < 0) putchar('-'), x = -x;
	if (x > 9) put(x / 10);
	putchar(x % 10 + '0');
}

bool isPrime(int x) {
	if (x <= 1) return false;
	int sqr = (int)sqrt(x * 1.0);
	for (int i = 2; i <= sqr; i++)
		if (x % i == 0) return false;
	return true;
}

void dfs(int cur, int sum, int begin) {
	if (cur == k) {
		if (isPrime(sum)) ans++;
		return;
	}
	for (int i = begin; i <= n; i++)
		dfs(cur + 1, sum + arr[i], i + 1);
}

int main() {
	n = read(), k = read();
	for (int i = 1; i <= n; i++) arr[i] = read();
	dfs(0, 0, 1);
	put(ans);
}

你可能感兴趣的:(递归)