結果

問題 No.2949 Product on Tree
ユーザー ooaiu
提出日時 2024-12-06 16:08:19
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 225 ms / 2,000 ms
コード長 1,672 bytes
コンパイル時間 3,583 ms
コンパイル使用メモリ 254,032 KB
実行使用メモリ 30,720 KB
最終ジャッジ日時 2024-12-06 16:08:41
合計ジャッジ時間 20,602 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 46
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

#ifdef LOCAL
#include "algo/debug.h"
#else
#define debug(...) (void(0))
#endif

#include <atcoder/modint>
using mint = atcoder::modint998244353;

namespace std {

template <class Fun>
class y_combinator_result {
    Fun fun_;

   public:
    template <class T>
    explicit y_combinator_result(T &&fun) : fun_(std::forward<T>(fun)) {}

    template <class... Args>
    decltype(auto) operator()(Args &&...args) {
        return fun_(std::ref(*this), std::forward<Args>(args)...);
    }
};

template <class Fun>
decltype(auto) y_combinator(Fun &&fun) {
    return y_combinator_result<std::decay_t<Fun>>(std::forward<Fun>(fun));
}

}  // namespace std
int main() {
    std::ios::sync_with_stdio(false);
    std::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 = 0; i < N - 1; i++) {
        int a, b; cin >> a >> b;
        a--, b--;
        G[a].push_back(b);
        G[b].push_back(a);
    }
    vector<mint> from(N), via(N);
    y_combinator([&](auto self, int v, int p = -1) -> void {
        from[v] = A[v];
        mint sum = 0;
        for(auto&&nv: G[v]) if(nv != p) {
            self(nv, v);
            from[v] += A[v] * from[nv];
            sum += from[nv];
        }
        for(auto&&nv: G[v]) if(nv != p) {
            sum -= from[nv];
            via[v] += sum * from[nv];
        }
        via[v] *= A[v];
    })(0);
    debug(from);
    debug(via);
    mint ans = 0;
    for(int i = 0; i < N; i++) {
        ans += from[i];
        ans += via[i];
        ans -= A[i];
    }
    cout << ans.val() << endl;
}
0