結果
問題 | No.2892 Lime and Karin |
ユーザー |
👑 ![]() |
提出日時 | 2024-09-13 22:49:29 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 171 ms / 8,000 ms |
コード長 | 3,531 bytes |
コンパイル時間 | 1,032 ms |
コンパイル使用メモリ | 86,900 KB |
最終ジャッジ日時 | 2025-02-24 08:05:55 |
ジャッジサーバーID (参考情報) |
judge2 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 52 |
ソースコード
#ifdef NACHIA#define _GLIBCXX_DEBUG#else#define NDEBUG#endif#include <iostream>#include <string>#include <vector>#include <algorithm>using i64 = long long;using u64 = unsigned long long;#define rep(i,n) for(int i=0; i<int(n); i++)const i64 INF = 1001001001001001001;template<typename A> void chmin(A& l, const A& r){ if(r < l) l = r; }template<typename A> void chmax(A& l, const A& r){ if(l < r) l = r; }#include <atcoder/modint>using Modint = atcoder::static_modint<998244353>;using namespace std;void testcase(){int N; cin >> N;vector<vector<int>> adj(N);rep(i,N-1){int u,v; cin >> u >> v; u--; v--;adj[u].push_back(v);adj[v].push_back(u);}vector<int> aw(N); {string s; cin >> s;rep(i,N) aw[i] = (s[i] == '1' ? 1 : -1);}vector<int> parent(N, -1);vector<int> Z(N, 1);{vector<int> bfs;bfs.push_back(0);rep(i,N){int v = bfs[i];for(int w : adj[v]) if(parent[v] != w){parent[w] = v;bfs.push_back(w);}}for(int i=N-1; i>=1; i--) Z[parent[bfs[i]]] += Z[bfs[i]];}//cout << "##" << endl;i64 ans = 0;auto flushTable = [&](int off, const vector<int>& c, int root) -> i64 {auto cs = vector<int>(c.size()+1);rep(i,c.size()) cs[i+1] += cs[i] + c[i];i64 cc = i64(cs.back()) * i64(cs.back());for(i64 i=0; i<i64(c.size()); i++){i64 j = off - (i + root - off);if(j >= 0) cc -= i64(c[i]) * i64(cs[min<i64>(cs.size() - 1, j + 1)]);}return cc;};//for(auto p : parent) cout << p << " ";//cout << endl;//for(auto p : Z) cout << p << " ";//cout << endl;auto cd = [&](auto& cd, int v) -> void {while(true){int nx = -1;for(int w : adj[v]) if(Z[w] * 2 > Z[v]){Z[v] -= Z[w]; Z[w] += Z[v];parent[v] = w; parent[w] = -1;nx = w;break;}if(nx >= 0) v = nx; else break;}//cout << "v = " << v << endl;int off = Z[v];vector<int> cnt(Z[v] * 2 + 1);cnt[off] += 1;int rootaw = aw[v];Z[v] = 0;for(int w : adj[v]) if(Z[w] != 0){//cout << "w = " << w << endl;parent[w] = -1;int offw = Z[w];vector<int> cntw(Z[w] * 2 + 1);vector<pair<int, int>> bfs;bfs.push_back({ w, 0 });rep(q,bfs.size()){auto [x,c] = bfs[q];//cout << "x = " << x << " , c = " << c << endl;c += aw[x];cntw[c + offw] += 1;cnt[c + off] += 1;for(int y : adj[x]) if(Z[y] != 0 && parent[x] != y){bfs.push_back({ y, c });}}//cout << "v = " << v << " , w = " << w << endl;//for(auto a : cntw) cout << a << " ";//cout << endl;ans -= flushTable(offw, cntw, aw[v]);cd(cd, w);}// cout << "v = " << v << endl;// for(auto a : cnt) cout << a << " ";// cout << endl;ans += flushTable(off, cnt, aw[v]);};rep(i,N) if(aw[i] > 0) ans += 1;cd(cd, 0);ans /= 2;cout << ans << endl;}int main(){ios::sync_with_stdio(false); cin.tie(nullptr);testcase();return 0;}