結果
| 問題 |
No.2949 Product on Tree
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2024-10-25 22:28:48 |
| 言語 | C++23 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 3,004 bytes |
| コンパイル時間 | 1,843 ms |
| コンパイル使用メモリ | 118,392 KB |
| 実行使用メモリ | 69,864 KB |
| 最終ジャッジ日時 | 2024-10-25 22:29:50 |
| 合計ジャッジ時間 | 53,351 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 40 WA * 6 |
ソースコード
#include <iostream>
#include <vector>
#include <map>
#include <utility>
#include <queue>
using namespace std;
using ll = long long;
ll mod_pow (ll x, ll p, const ll MOD) {
x %= MOD;
ll res = 1;
while (0 < p) {
if (p % 2 == 1) {
res *= x;
res %= MOD;
}
p >>= 1;
x *= x;
x %= MOD;
}
return res;
}
int main () {
int N; cin >> N;
vector<int> A(N);
for (int i = 0; i < N; i++) cin >> A[i];
vector<vector<int>> graph(N);
for (int i = 0; i < N - 1; i++) {
int U, V; cin >> U >> V;
U--, V--;
graph[U].push_back(V);
graph[V].push_back(U);
}
const ll MOD = 998244353;
// (i, j)全列挙は回らないので、主客転倒的数え上げが必要そう。
// 根rを決めて、rからの全パスの積の和と考えてみる。
// (子の総和 + 1) * (重み)を渡す木dpで出来そう。
// -> 全方位木dpに乗りますよねこれ
map<pair<int, int>, ll> dp;
// dp[(i, j)] := 根i、親jのミニ部分木での解
{
auto dfs = [&] (auto& dfs, int pos, int par) -> void {
ll v = 1;
for (auto nex : graph[pos]) {
if (nex == par) continue;
dfs(dfs, nex, pos);
v += dp[make_pair(nex, pos)];
}
v %= MOD;
v *= A[pos];
v %= MOD;
dp[make_pair(pos, par)] = v;
};
dfs(dfs, 0, -1);
}
{ // BFSで伝搬
queue<int> q;
vector<bool> vis(N);
vector<ll> L(N), R(N);
q.push(0);
vis[0] = true;
while (!q.empty()) {
auto pos = q.front(); q.pop();
const int ch_size = static_cast<int> (graph[pos].size());
// 累積和の計算
L[0] = 0;
for (int i = 0; i < ch_size; i++) {
int nex = graph[pos][i];
L[i + 1] = L[i] + dp[make_pair(nex, pos)] % MOD;
}
R[0] = 0;
for (int i = 0; i < ch_size; i++) {
int nex = graph[pos][ch_size - i - 1];
R[i + 1] = R[i] + dp[make_pair(nex, pos)] % MOD;
}
// 逆向き伝搬
for (int i = 0; i < ch_size; i++) {
int nex = graph[pos][i];
if (vis[nex]) continue;
ll v = (L[i] + R[ch_size - i - 1] + 1) % MOD;
v *= A[pos];
v %= MOD;
dp[make_pair(pos, nex)] = v;
vis[nex] = true;
q.push(nex);
}
// 自分を根とする値の計算
dp[make_pair(pos, -1)] = (L[ch_size] + 1) * A[pos] % MOD;
}
}
ll ans = 0;
for (int i = 0; i < N; i++) {
ans += dp[make_pair(i, -1)] - A[i];
ans %= MOD;
}
ans *= mod_pow(2, MOD - 2, MOD);
ans %= MOD;
if (ans < 0) ans += MOD;
cout << ans << "\n";
}