美文网首页
A1048 Find Coins (25 points)hash

A1048 Find Coins (25 points)hash

作者: zilla | 来源:发表于2019-07-11 18:46 被阅读0次

    A1048 Find Coins

    哈希写法

    • 硬币面值有限且为整数,可直接作为下标,计数即可。
    #include <cstdio>
    
    using namespace std;
    
    int main() {
        int coins[1001] = {0}, nn, total, value;
        scanf("%d%d", &nn, &total);
        for (int i = 0; i < nn; ++i) {
            scanf("%d", &value);
            coins[value]++;
        }
        bool ok = false;
        for (int i = 1; i <= total / 2; ++i) {
            if (coins[i]) {
                if (coins[total - i]) {
                    if (total - i != i || (total - i == i && coins[i] >= 2)) {
                        printf("%d %d\n", i, total - i);
                        ok = true;
                        break;
                    }
                }
            }
        }
        if (!ok)
            puts("No Solution");
        return 0;
    }
    

    排序➕二分

    #include <cstdio>
    #include <algorithm>
    
    using namespace std;
    
    int main() {
        int coins[100010], nn, total, c1 = 0, c2 = 0;
        scanf("%d%d", &nn, &total);
        for (int i = 0; i < nn; i++)
            scanf("%d", &coins[i]);
        sort(coins, coins + nn);
        for (int i = 0; i < nn - 1; ++i) {
            int target = total - coins[i];
            int index = lower_bound(coins + i + 1, coins + nn, target) - coins;
            if (coins[index] == target) {
                c1 = coins[i], c2 = coins[index];
                break;
            }
        }
        if (c1 == 0)
            puts("No Solution");
        else printf("%d %d\n", c1, c2);
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:A1048 Find Coins (25 points)hash

          本文链接:https://www.haomeiwen.com/subject/ujqjkctx.html