怎么去分析这个题目,一开始我想的就是暴力dfs,接着枚举删除的节点,但是只过了百分之四十个点,代码如下:(这个代码有点像树形dp)
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = (int)1e5+5;
int e[N],ne[N],h[N],idx = 0;
int n;
int a[N];
int vis[N]; // 设置分开的树
void add(int a,int b){
e[++idx] = b, ne[idx] = h[a],h[a] = idx;
}
int ans = 0;
int dfs(int node,int wei){ // 返回值是该节点的子节点的权重
int now = a[node]; // 该节点的权重
int big = 0;
int sum = 0;
for(int i=h[node];i;i=ne[i]){
int to = e[i];
if(vis[to]) continue;
int t = dfs(to,wei+now);
sum += t; // 统计总的数量
big = max(big,t);
}
if(now<=wei&& now>=sum){
ans ++;
//cout << " 节点 " << node << endl;
}
return now+sum;
}
signed main(){
cin >> n;
for(int i=1;i<=n;i++){
cin >> a[i];
}
int temp; cin >> temp;
for(int i=2;i<=n;i++){
int fa; cin >> fa;
add(fa,i);
}
int last = 0;
for(int i=2;i<=n+1;i++){
ans = 0;
vis[i] = 1;
dfs(1,0);
vis[i] = 0;
last = max(last,ans);
//cout << endl;
}
cout << last;
return 0;
}
但是复杂度太高了,那有没有什么办法呢,我们注意到,当我们删除一个节点的时候,影响的是什么?我们会失去以这个节点为树 的所有答案,但是,这个节点的祖先节点中 如果 存在之前不满足 w[u] > sum[u] 的,现在满足 w[u] > sum[u] - w[v] 的,这个要加上答案里面
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
typedef long long ll;
const int N = 1e5 + 10,M=2e5+10;
ll n, w[N], sum[N], mark[N],ans[N],tr[M],idx,res;
map<ll, ll>m;
vector<ll>a[N],b;
ll lowbit(ll x) {
return x & -x;
}
void add(int x, int val) {
for (; x <= idx; x += lowbit(x))
tr[x] += val;
}
ll query(int x) {
ll res = 0;
for (; x; x -= lowbit(x))
res += tr[x];
return res;
}
void dfs(int u, int fa, int all) {
if (all >= w[u])
mark[u] = 1;
for (int i = 0; i < a[u].size(); i++) {
int v = a[u][i];
if (v == fa)
continue;
dfs(v, u, all + w[u]);
ans[u]+=ans[v];
sum[u] += sum[v];
}
if (mark[u]) {
if (sum[u] <= w[u])
ans[u]++;
else b.push_back(sum[u] - w[u]);
}
sum[u] += w[u];
b.push_back(sum[u]);
}
void dfs(int u, int fa) {
if (mark[u] && w[u] < sum[u] - w[u])
add(m[sum[u] - 2 * w[u]], 1);
for (int i = 0; i < a[u].size(); i++) {
int v = a[u][i];
if (v == fa)continue;
res = max(res, ans[1] - ans[v] + query(m[sum[v]]));
dfs(v, u);
}
if (mark[u] && w[u] < sum[u] - w[u])
add(m[sum[u] - 2 * w[u]], -1);
}
void solve() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> w[i];
}
for (ll i = 1; i <= n; i++) {
ll fa;
cin >> fa;
a[fa].push_back(i);
a[i].push_back(fa);
}
dfs(1, 0, 0);
sort(b.begin(),b.end());
for (int i = 0; i < b.size(); i++) {
if (!m.count(b[i]))
m[b[i]] = ++idx;
}
dfs(1,0);
cout << max(res, ans[1]) << "\n";
}
int main() {
int t = 1;
//cin >> t;
while (t--)
solve();
}