CF682C Alyona and the Tree

题意翻译

题目描述

给你一棵树,边与节点都有权值,根节点为1,现不停删除叶子节点形成新树,问最少删掉几个点,能使得最后剩下的树内,v与其子树内u间边权的和小于点u权值

输入输出格式

输入格式:

第一行,节点个数n(1n1e5)

第二行,n个整数——各节点的权值ai(1ai1e9)

接下来的n-1行,每行两个整数pici(1pin,1e9ci1e9),分别表示编号为i+1的节点的父节点以及该边的边权

输出格式:

一个整数,最少需要删除的点的个数

输入输出样例

输入样例#1: 
9
88 22 83 14 95 91 98 53 11
3 24
7 -8
1 67
1 64
9 65
5 12
6 -80
3 8
输出样例#1: 
5

代码

思维题。

首先可以转化成保留多少个节点。

然后每次累加取max(0,sum+e[i].val)

比如说我们v[u]=10,而此时sum=-1000,而∑e[i].val=20,显然这种情况是不可法的

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+100;
int v[maxn],head[maxn];
struct edge
{
    int to,next,val;
}e[maxn];
int cnt=0;
int size=0;
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+ch-'0';ch=getchar();}
    return x*f;
}
void addedge(int u,int v,int w)
{
    e[++size].to=v;e[size].val=w;e[size].next=head[u];head[u]=size;
}
void dfs(int u,int sum)
{
    if(sum>v[u])return;
    cnt++;
    for(int i=head[u];i;i=e[i].next)
    {
        int to=e[i].to;
        dfs(to,max(0,sum+e[i].val));
    }
}
int main()
{
    int n=read();
    for(int i=1;i<=n;i++)
    v[i]=read();
    for(int i=2;i<=n;i++)
    {
        int v=read(),w=read();
        addedge(v,i,w);
    }
    dfs(1,0);
    printf("%d",n-cnt);
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/DriverBen/p/11001768.html