Submission #1026520

#TimeUsernameProblemLanguageResultExecution timeMemory
1026520WhisperZagrade (COI17_zagrade)C++17
100 / 100
754 ms56552 KiB
#include <bits/stdc++.h> using namespace std; using ll = long long; #define int long long #define FOR(i, a, b) for (int i = (a); i <= (b); i++) #define FORD(i, a, b) for (int i = (b); i >= (a); i --) #define REP(i, n) for (int i = 0; i < (a); ++i) #define REPD(i, n) for (int i = (a) - 1; i >= 0; --i) #define MASK(i) (1LL << (i)) #define BIT(x, i) (((x) >> (i)) & 1) constexpr ll LINF = (1ll << 60); constexpr int INF = (1ll << 30); constexpr int Mod = 1e9 + 7; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); /* Phu Trong from Nguyen Tat Thanh High School for gifted student */ template <class X, class Y> bool minimize(X &x, const Y &y){ X eps = 1e-9; if (x > y + eps) {x = y; return 1;} return 0; } template <class X, class Y> bool maximize(X &x, const Y &y){ X eps = 1e-9; if (x + eps < y) {x = y; return 1;} return 0; } #define MAX 300005 int numNode; string s; vector<int> G[MAX]; int sz[MAX], del[MAX], label[MAX]; void reSubsize(int u, int p = -1){ sz[u] = 1; for (int &v : G[u]) if(v ^ p){ if (del[v]) continue; reSubsize(v, u); sz[u] += sz[v]; } } int findCentroid(int u, int p, int siz){ for (int &v : G[u]) if(v ^ p){ if(del[v]) continue; if (2 * sz[v] > siz) return findCentroid(v, u, siz); } return u; } map<int, int> cnt; int ans = 0; void dfs(int u, int p, int pref, int mxpref, int mnpref, bool add){ pref += label[u]; maximize(mxpref, pref); minimize(mnpref, pref); if(add){ if (-pref + mxpref <= 0 && pref >= 0){ cnt[pref]++; } } else{ if (-pref + mnpref >= 0){ assert(pref <= 0); ans += 1LL * cnt[-pref]; } } for (int&v : G[u]) if(v ^ p){ if (!del[v]) { dfs(v, u, pref, mxpref, mnpref, add); } } } void decompose(int root){ reSubsize(root); int siz = sz[root]; root = findCentroid(root, root, siz); cnt.clear(); del[root] = 1; if(label[root] != -1) cnt[label[root]]++; for (int&v : G[root]) if(!del[v]){ dfs(v, root, 0, 0, 0, 0); dfs(v, root, label[root], label[root], label[root], 1); } ans += 1LL * cnt[0]; cnt.clear(); reverse(G[root].begin(), G[root].end()); for (int&v : G[root]) if(!del[v]){ dfs(v, root, 0, 0, 0, 0); dfs(v, root, label[root], label[root], label[root], 1); } for (int&v : G[root]) if(!del[v]){ decompose(v); } } void process(void){ cin >> numNode >> s; for (int i = 1; i <= numNode; ++i) label[i] = (s[i - 1] == '(' ? 1 : -1); for (int i = 1; i < numNode; ++i){ int u, v; cin >> u >> v; G[u].emplace_back(v); G[v].emplace_back(u); } decompose(1); cout << ans; } signed main(){ #define name "Whisper" cin.tie(nullptr) -> sync_with_stdio(false); //freopen(name".inp", "r", stdin); //freopen(name".out", "w", stdout); process(); return (0 ^ 0); }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...