이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
/// dwuy: _,\,,,_\,__,\,,_
#include <bits/stdc++.h>
#define fastIO ios_base::sync_with_stdio(false); cin.tie(NULL)
#define file(a) freopen(a".inp","r",stdin); freopen(a".out", "w",stdout)
#define fi first
#define se second
#define endl "\n"
#define len(s) int32_t(s.length())
#define MASK(k)(1LL<<(k))
#define TASK ""
#define int long long
using namespace std;
typedef tuple<int, int, int> tpiii;
typedef pair<double, double> pdd;
typedef pair<int, int> pii;
typedef long long ll;
const long long OO = 1e18;
const int MOD = 1e9 + 7;
const int INF = 1e9;
const int MX = 300005;
int n;
string a;
vector<int> G[MX];
void nhap(){
cin >> n;
cin >> a; a = ' ' + a;
for(int i=1; i<n; i++){
int u, v;
cin >> u >> v;
G[u].push_back(v);
G[v].push_back(u);
}
}
int numC[MX];
bitset<MX> vist = 0;
void calChild(int u){
vist[u] = 1;
numC[u] = 1;
for(int v: G[u]) if(!vist[v]){
calChild(v);
numC[u] += numC[v];
}
vist[u] = 0;
}
int centroid(int u, int p, const int &half){
for(int v: G[u]) if(v!=p && !vist[v]){
if(numC[v] > half) return centroid(v, u, half);
}
return u;
}
int p[MX];
int op[MX];
int cl[MX];
int fop[MX];
int fcl[MX];
int c1(char c){
return c==')'? 1 : -1;
}
int c2(char c){
return -c1(c);
}
int getmap(int val, const map<int, int> &mp){
auto itr = mp.find(val);
return itr == mp.end()? 0 : itr->se;
}
int calc(int u){
int res = 0;
map<int, int> mp1, mp2;
if(c1(a[u]) < 0) mp1[-1]++;
for(int v: G[u]) if(!vist[v]){
vector<int> node1, node2;
stack<int> Q;
Q.push(v);
p[v] = u;
op[v] = c1(a[u]) + c1(a[v]);
cl[v] = c2(a[v]);
fop[v] = min({0LL, c1(a[u]), op[v]});
fcl[v] = min(0LL, c2(a[v]));
while(Q.size()){
int u = Q.top();
Q.pop();
if(cl[u] == fcl[u]){
res += getmap(cl[u], mp1);
node2.push_back(u);
}
if(op[u] == fop[u]){
res += getmap(op[u], mp2);
node1.push_back(u);
}
for(int v: G[u]) if(!vist[v] && v!=p[u]){
Q.push(v);
p[v] = u;
op[v] = op[u] + c1(a[v]);
cl[v] = cl[u] + c2(a[v]);
fop[v] = min(fop[u], op[v]);
fcl[v] = min(fcl[u], cl[v]);
}
}
for(int u: node1) mp1[op[u]]++, res += op[u]==0;
for(int u: node2) mp2[cl[u]]++;
}
return res;
}
int solve(int u){
calChild(u);
u = centroid(u, 0, numC[u]>>1);
int res = calc(u);
vist[u] = 1;
for(int v: G[u]) if(!vist[v]) res += solve(v);
return res;
}
int32_t main(){
fastIO;
//file(TASK);
nhap();
cout << solve(1);
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |