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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章