Submission #698573

#TimeUsernameProblemLanguageResultExecution timeMemory
698573jcelinZagrade (COI17_zagrade)C++14
100 / 100
1389 ms76840 KiB
#include <bits/stdc++.h> //#include<ext/pb_ds/assoc_container.hpp> //#include<ext/pb_ds/tree_policy.hpp> using namespace std; //using namespace __gnu_pbds; typedef long long ll; typedef long double ld; #define ii pair<int,int> #define pll pair<ll,ll> #define vi vector<int> #define vii vector<ii> #define vll vector<ll> #define vpll vector<pll> #define msi multiset<int> #define si set<int> #define PB push_back #define PF push_front #define PPB pop_back #define PPF pop_front #define X first #define Y second #define MP make_pair #define FOR(i, a, b) for (int i = int(a); i < int(b); i++) #define REP(i, n) FOR(i, 0, n) #define all(x) (x).begin(), (x).end() const int dx[] = {-1, 1, 0, 0}; const int dy[] = {0, 0, -1, 1}; const int dxx[] = {-1, 1, 0, 0, 1, 1, -1, -1}; const int dyy[] = {0, 0, -1, 1, -1, 1, -1, 1}; const int mod = 1e9 + 7; const int MOD = 1e9 + 7; const int MAXN = 1e6 + 7; const int inf = mod; const ll INF = 1e18; const int logo = 20; const int off = 1 << logo; const int trsz = off << 1; string s; int n, sz[MAXN]; bool bio[MAXN]; ll ans = 0; vi g[MAXN]; map<ii, int> f; void dfs(int u, int p = -1){ sz[u] = 1; for(auto &x : g[u]) if(x != p and !bio[x]) dfs(x, u), sz[u] += sz[x]; } int cen(int u, int p, int szi){ for(auto &x : g[u]) if(x != p and !bio[x]) if(sz[x] * 2 > szi) return cen(x, u, szi); return u; } void dodaj(int x, int t, int a = 0, int b = 0, int p = -1){ if(s[x] == '(') a++; else{ if(a) a--; else b++; } f[{a, b}] += t; for(auto &y : g[x]) if(!bio[y] and y != p) dodaj(y, t, a, b, x); } void rijesi(int x, int centr, int a = 0, int b = 0, int p = -1){ if(s[x] == ')') b++; else{ if(b) b--; else a++; } int na = a, nb = b; if(s[centr] == '(') na++; else{ if(na) na--; else nb++; } if(nb == 0) ans += (ll)f[{0, na}]; for(auto &y : g[x]) if(!bio[y] and y != p) rijesi(y, centr, a, b, x); } void decompose(int u){ dfs(u); int centr = cen(u, -1, sz[u]); //sad napravi rjesenje bio[centr] = 1; f.clear(); f[{0, 0}] = 1; for(auto &x : g[centr]) if(!bio[x]) dodaj(x, 1); if(s[centr] == '(') ans += (ll)f[{0, 1}]; for(auto &x : g[centr]){ if(bio[x]) continue; dodaj(x, -1); rijesi(x, centr); dodaj(x, 1); } for(auto &x : g[centr]) if(!bio[x]) decompose(x); } void solve(){ cin >> n >> s; REP(i, n - 1){ int a, b; cin >> a >> b; a--, b--; g[a].PB(b); g[b].PB(a); } dfs(0); decompose(0); cout << ans << "\n"; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t=1; //cin >> t; while(t--)solve(); return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...