1 title
Problems C: [recursive entry] composition + Analyzing prime
time limit: 1 Sec memory limit: 128 MB
submission: 2125 solution: 615
[Submit] [state] [discussion boards] [proposition al: External Import]
Title Description
known in the n integers b1, b2, ..., bn
And an integer k (k <n).
Optionally adding integers k from n integers in a range of available respectively.
For example, when n = 4, k = 3,4 integers, respectively, is 3,7,12,19, available all combinations of thereof and is:
3 + 7 + 12 = 223 + 7 + 19 = 297 + 12 + 19 = 383 + 12 + 19 = 34.
Now, we ask you to calculate the total number of species and is a prime number.
For example the embodiment, only one, and is a prime number: 3 + 7 + 19 = 29.
Input
of the first rows of two integers: n, k (1 <= n <= 20, k <n)
a second row of n integers: x1, x2, ..., xn (1 <= xi <= 5000000)
Output
an integer (number satisfying the condition of the program).
样例输入
4 3
3 7 12 19
样例输出
1
2 reference code
#include <cstdio>
#include <cmath>
#include <vector>
using std::vector;
typedef long long LL;
const int MAXN = 25;
int N,K;
int Count = 0;
LL A[MAXN], res[MAXN];
bool hashTable[MAXN] = {false};
bool isPrime(LL x){
if(x <= 1) return false;
LL sqr = (LL) sqrt(1.0 * x);
for (LL i = 2; i <= sqr; ++i)
{
if(x % i == 0) return false;
}
return true;
}
void BFS(int index, int r){
if(r == K + 1){
int sum = 0;
for (int i = 1; i != K + 1; ++i) {
sum += res[i];
}
if(isPrime(sum) == true){
Count++;
// for (int j = 1; j != K + 1; ++j) {
// printf("%lld ", res[j]);
// }
// printf("\n");
}
return;
}
for (int i = index; i <= N; ++i)
{
if(hashTable[i] == false){
res[r] = A[i];
hashTable[i] = true;
BFS(i, r + 1);
hashTable[i] = false;
}
}
}
int main(int argc, char const *argv[])
{
scanf("%d%d", &N, &K);
for (int i = 1; i != N + 1; ++i)
{
scanf("%lld", &A[i]);
}
BFS(1,1);
printf("%d\n", Count);
return 0;
}
- Reference code 2
#include <cstdio>
#include <cmath>
#include <vector>
using std::vector;
typedef long long LL;
const int MAXN = 25;
int N,K;
int Count = 0;
LL A[MAXN];
int sum = 0;
bool isPrime(LL x){
if(x <= 1) return false;
LL sqr = (LL) sqrt(1.0 * x);
for (LL i = 2; i <= sqr; ++i)
{
if(x % i == 0) return false;
}
return true;
}
void BFS(int index, int r){
if(r == K + 1){
if(isPrime(sum) == true){
Count++;
}
return;
}
for (int i = index; i <= N; ++i)
{
sum += A[i];
BFS(i + 1, r + 1);
sum -= A[i];
}
}
int main(int argc, char const *argv[])
{
scanf("%d%d", &N, &K);
for (int i = 1; i != N + 1; ++i)
{
scanf("%lld", &A[i]);
}
BFS(1,1);
printf("%d\n", Count);
return 0;
}