QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#621473 | #7736. Red Black Tree | SCAU_xyjkanade | RE | 0ms | 0kb | C++14 | 1.4kb | 2024-10-08 14:45:01 | 2024-10-08 14:45:12 |
answer
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n;
int T;
int ans[N];
char s[N];
vector<int> e[N];
pair<int, vector<int>> dfs(int sn) {
vector<int> cf;
int v = 0;
for (int i : e[sn]) {
auto [val, depth] = dfs(i);
v += val;
if (cf.empty()) {
cf = depth;
} else {
int sz = min(cf.size(), depth.size());
for (int i = 0; i < sz; i++) {
cf[i] += depth[i];
}
}
}
v += s[sn] - '0';
if (s[sn] == '0') {
cf.push_back(1);
} else {
cf.push_back(-1);
for (int& d : cf) d--;
}
ans[sn] = v + accumulate(begin(cf), end(cf), 0);
return {v, cf};
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> T;
while (T--) {
cin >> n;
scanf("%s", s + 1); // 使用 scanf 读取字符串,因为可能包含空格
for (int i = 1; i <= n; i++) {
e[i].clear();
}
for (int i = 2; i <= n; i++) {
int x;
cin >> x;
e[x].push_back(i);
}
dfs(1);
for (int i = 1; i <= n; i++) {
cout << ans[i] << (i < n ? " " : "\n");
}
}
return 0;
}
详细
Test #1:
score: 0
Runtime Error
input:
2 9 101011110 1 1 3 3 3 6 2 2 4 1011 1 1 3