BestCoder Round #78 CA Loves GCD

題目鏈接

http://acm.hdu.edu.cn/showproblem.php?pid=5655

代碼

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <map>
#include <vector>
using namespace std;

int T;
long long a[4];
int main() {
    scanf("%d",&T);
    while(T --) {
               scanf("%I64d%I64d%I64d%I64d",&a[0],&a[1],&a[2],&a[3]);
        sort(a,a + 4);
        bool ok = true;
        if(a[0] <= 0) ok = false;
        if(a[0] <= a[3] - a[1] - a[2]) ok = false;

        if(ok) puts("Yes");
        else puts("No");

    }
}

題目 CA Loves GCD

http://acm.hdu.edu.cn/showproblem.php?pid=5656

問題描述

CA喜歡是一個熱愛黨和人民的優秀同♂志,所以他也非常喜歡GCD(請在輸入法中輸入GCD得到CA喜歡GCD的原因)。
現在他有N個不同的數,每次他會從中選出若干個(至少一個數),求出所有數的GCD然後放回去。
爲了使自己不會無聊,CA會把每種不同的選法都選一遍,CA想知道他得到的所有GCD的和是多少。
我們認爲兩種選法不同,當且僅當有一個數在其中一種選法中被選中了,而在另外一種選法中沒有被選中。

輸入描述

第一行 TT,表示有 TT 組數據。
TTNNCANNAiAiCA1T50, 1N1000, 1Ai10001T50,1N1000,1Ai1000

輸出描述

對於每組數據輸出一行一個整數表示CA所有的選法的GCD的和對 100000007100000007 取模的結果。

輸入樣例

2
2
2 4
3
1 2 3

輸出樣例

8
10

思路

  • dp[i][j] 表示用前i個數字湊成gcd=j的所有可能。
  • 如果使用了第a[i + 1] 那麼,dp[i + 1][gcd(j,a[i + 1])] += dp[i][j]; 否則dp[i + 1][j] += dp[i][j];

代碼

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;

int T;
int n;
const int MAXN = 1005;
int a[MAXN];
int dp[MAXN][MAXN];
int GCD[MAXN][MAXN];
int gcd(int x,int y) { 
    if(x == 0) return y;
    return gcd(y % x,x);
}
const int MOD = 100000007;
int main() {
    for (int i = 0;i <= 1000;i ++) {
        for (int j = 0;j <= 1000;j ++) {
            GCD[i][j] = gcd(i,j);
        }
    }
    scanf("%d",&T);
    while(T --) {
        memset(dp,0,sizeof(dp));
        scanf("%d",&n);
        int maxs = 0;
        for (int i = 1;i <= n;i ++) {
            scanf("%d",&a[i]);
            maxs = max(maxs,a[i]);
        }
        dp[0][0] = 1;
        for (int i = 0;i + 1 <= n;i ++) {
            for (int j = 0;j <= maxs;j ++) {
                (dp[i + 1][j] += dp[i][j]) %= MOD;
                (dp[i + 1][GCD[j][a[i + 1]]] += dp[i][j]) %= MOD;
            }
        }
        int ret = 0;
        for (int i = 0;i <= 1000;i ++) {
            ret = (ret + ((long long)dp[n][i]) * i % MOD) % MOD;
        }
        printf("%d\n",ret);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章