問題C:[エントリー]再帰決意組成物の素数+

1タイトル

問題C:[再帰エントリ】組成物+プライム分析
制限時間:1秒メモリ制限:128 MBの
提出:2125溶液:615
[登録] [状態] [掲示板] [命題ら:外部インポート]
タイトル説明
Nで公知整数B1、B2、...、BN

整数K(K <N)。

必要に応じてそれぞれ使用可能の範囲でnは整数の整数kを加えます。

例えば、N = 4、K = 3,4の整数で、それぞれ、利用可能な3,7,12,19、それらのすべての組み合わせであるときである:
    3 + 7 + 12 = 223 + 7 + 19 = 297 + 12 + 19 = 383 + 12 + 19 = 34。
  今、私たちは種の合計数を計算するように依頼し、素数です。

+ 7 3 + 19 = 29:たとえば、実施形態は、一つだけ、そして素数です。

入力
二つの整数の最初の行:N、K(1 <= N <= 20、K <n)の
2行目のnは整数:X1、X2、...、XN (1 <= XI <= 5000000)

出力
整数(プログラムの条件を満足する数値)。

样例输入
4 3
3 7 12 19
样例输出
1

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], 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;
}


  • リファレンスコード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;
}

公開された321元の記事 ウォン称賛51 ビュー40000 +

おすすめ

転載: blog.csdn.net/qq_33375598/article/details/104074548