結果

問題 No.3502 GCD Knapsack
コンテスト
ユーザー gojoxd
提出日時 2026-04-18 18:21:35
言語 C
(gcc 15.2.0)
コンパイル:
gcc-15 -O2 -DONLINE_JUDGE -o a.out _filename_ -lm
実行:
./a.out
結果
AC  
実行時間 30 ms / 2,000 ms
コード長 1,194 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 601 ms
コンパイル使用メモリ 38,988 KB
実行使用メモリ 6,784 KB
最終ジャッジ日時 2026-04-18 18:21:39
合計ジャッジ時間 2,949 ms
ジャッジサーバーID
(参考情報)
judge1_0 / judge2_1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 35
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include <stdio.h>
#include <string.h>

#define MAXV 200001

// For each weight value v, store sum of Y values of items with X_i == v
long long sum_at[MAXV];
// Track if any item exists at weight v
int has_item[MAXV];

int main(void) {
    int N, W;
    scanf("%d %d", &N, &W);

    int X[N];
    long long Y[N];
    int max_x = 0;

    for (int i = 0; i < N; i++) {
        scanf("%d", &X[i]);
        if (X[i] > max_x) max_x = X[i];
    }
    for (int i = 0; i < N; i++) {
        scanf("%lld", &Y[i]);
    }

    // Accumulate values at each weight
    memset(sum_at, 0, sizeof(sum_at));
    for (int i = 0; i < N; i++) {
        sum_at[X[i]] += Y[i];
        has_item[X[i]] = 1;
    }

    long long ans = 0;

    // Sieve: for each candidate GCD g >= W, sum all items whose weight is divisible by g
    for (int g = W; g <= max_x; g++) {
        long long total = 0;
        int found = 0;
        for (int mult = g; mult <= max_x; mult += g) {
            if (has_item[mult]) {
                total += sum_at[mult];
                found = 1;
            }
        }
        if (found && total > ans) {
            ans = total;
        }
    }

    printf("%lld\n", ans);
    return 0;
}
0