結果

問題 No.2949 Product on Tree
ユーザー nonon
提出日時 2024-10-26 09:20:16
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 184 ms / 2,000 ms
コード長 939 bytes
コンパイル時間 3,202 ms
コンパイル使用メモリ 253,432 KB
実行使用メモリ 27,820 KB
最終ジャッジ日時 2024-10-26 09:20:32
合計ジャッジ時間 15,567 ms
ジャッジサーバーID
(参考情報)
judge5 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 46
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#include <atcoder/modint>
using namespace std;
using mint = atcoder::modint998244353;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int N;
    cin >> N;
    vector<int> A(N);
    for (int i = 0; i < N; i++) cin >> A[i];
    vector<vector<int>> G(N);
    for (int i = 1; i < N; i++) {
        int u, v;
        cin >> u >> v;
        u-- ,v--;
        G[u].push_back(v);
        G[v].push_back(u);
    }
    vector<mint> S(N);
    mint ans = 0;
    const mint inv2 = mint::raw(2).inv();
    auto dfs = [&](const auto &dfs, int u, int p) -> void {
        mint s = 0, ss = 0;
        for (int v : G[u]) {
            if (v != p) {
                dfs(dfs, v, u);
                s += S[v];
                ss += S[v] * S[v];
            }
        }
        S[u] = A[u] * (s + 1);
        ans += A[u] * (s + (s * s - ss) * inv2);
    };
    dfs(dfs, 0, -1);
    cout << ans.val() << endl;
}
0