题解:#166.B、选数 审核通过

csp1 2024-11-24 12:18:52 6

本题做法

  1. DFS,写好组合函数
void dfs(int start, int count, int sum) {
	if (count == k && _____________) {
		ans++;
	}

	for (int i = start; i <= n; i++) {
        dfs(i + 1, count + 1, sum + sz[i]);

	}
}
  1. 由于本题又不是随便选,要判断质数
bool isPrime(int i) {
    if (i==2) return 1;
    for (int j = 2; j*j <= i; j++) {
		if (i%j == 0) {
			return false;
		}
	}
	return true;
}

  1. 注意Freopen

完整代码

#include <bits/stdc++.h>
using namespace std;

int ans=0;
int n,k;
int sz[26];

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

void dfs(int start, int count, int sum) {
	if (count == k && isPrime(sum)) {
		ans++;
	}

	for (int i = start; i <= n; i++) {
        dfs(i + 1, count + 1, sum + sz[i]);

	}
}

int main() {
	freopen("B.in","r",stdin);
	freopen("B.out","w",stdout);
	int i;
	cin >> n >> k;
	for (i = 1; i <= n; i++) {
		cin >> sz[i];
	}
	dfs(1, 0, 0);
	cout << ans << endl;
	return 0;
}
{{ vote && vote.total.up }}