洛谷 P5658 括号树
自己没什么思路,就看了看第一篇题解,简直不要讲的太好!自愧不如,下面给出链接,去看他吧!
墨攸的题解 P5658 【括号树】
\(50pts\)
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int A = 5e5 + 11;
const int B = 1e6 + 11;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
inline int read() {
char c = getchar(); int x = 0, f = 1;
for( ; !isdigit(c); c = getchar()) if(c == '-') f = -1;
for( ; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48);
return x * f;
}
struct node {
int nxt, to;
} e[A << 1];
int n, cnt, head[A], f[A], ans[A], top = 0;
char sta[A], ss[A], a[A];
inline void add(int from, int to) {
e[++cnt].to = to;
e[cnt].nxt = head[from];
head[from] = cnt;
}
int jisuan() {
int tp = 0, res = 0;
for(int i = top; i >= 1; i--) {
if(sta[i] == ')') ++tp;
else {
if(tp > 0) tp--;
else break;
}
if(tp == 0) res++;
}
return res;
}
void dfs(int now, int fa) {
for(int i = head[now]; i; i = e[i].nxt) {
int to = e[i].to;
sta[++top] = a[to];
if(a[to] == '(') ans[to] = ans[now];
else ans[to] = ans[now] + jisuan();
dfs(to, now);
top--;
}
}
int main() {
n = read(); scanf("%s", a + 1);
for(int i = 2, x; i <= n; i++) {
x = read();
f[i] = x;
add(x, i);
}
sta[++top] = a[1];
dfs(1, 0);
int sum = 0;
for(int i = 1; i <= n; i++) {
sum ^= (i * ans[i]);
}
cout << sum << '\n';
return 0;
}
\(100pts\):
/*
Author:loceaner
*/
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int A = 5e5 + 11;
const int B = 1e6 + 11;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
inline int read() {
char c = getchar(); int x = 0, f = 1;
for( ; !isdigit(c); c = getchar()) if(c == '-') f = -1;
for( ; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48);
return x * f;
}
char s[A];
long long ans, f[A], sum[A];
struct node { int to, nxt; } e[A];
int n, cnt, top, fa[A], sta[A], head[A];
inline void add(int from, int to) {
e[++cnt].to = to;
e[cnt].nxt = head[from];
head[from] = cnt;
}
void dfs(int x) {
int tmp = 0;
if (s[x] == ')') {
if (top) tmp = sta[top--], f[x] = f[fa[tmp]] + 1;
}
else sta[++top] = x;
sum[x] = sum[fa[x]] + f[x];
for (int i = head[x]; i; i = e[i].nxt) dfs(e[i].to);
if (tmp) sta[++top] = tmp;
else if (top) top--;
}
int main() {
n = read();
scanf("%s", s + 1);
for (int i = 2; i <= n; i++) add(fa[i] = read(), i);
dfs(1);
for (int i = 1; i <= n; i++) ans ^= sum[i] * i * 1ll;
cout << ans << '\n';
return 0;
}
转载不必联系作者,但请声明出处