码迷,mamicode.com
首页 > 其他好文 > 详细

【Luogu】P3574FAR_FarmCraft(树形贪心)

时间:2018-01-25 15:46:14      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:show   getch   htm   craft   str   include   algorithm   题目   class   

  题解链接

  想了一个错的贪心爆零了,气死。

  题目链接

#include<cstdio>
#include<cctype>
#include<cstring>
#include<algorithm>
#include<cstring>
#define maxn 500050
using namespace std;

inline long long read(){
    long long num=0,f=1;
    char ch=getchar();
    while(!isdigit(ch)){
        if(ch==-)    f=-1;
        ch=getchar();
    }
    while(isdigit(ch)){
        num=num*10+ch-0;
        ch=getchar();
    }
    return num*f;
}

struct Edge{
    int next,to;
}edge[maxn*2];
int head[maxn],num;
inline void add(int from,int to){
    edge[++num]=(Edge){head[from],to};
    head[from]=num;
}

long long q[maxn];
long long f[maxn];
long long s[maxn];
int sta[maxn],top;

bool cmp(int a,int b){    return f[a]>f[b];    }

void dfs(int x,int fa){
    int ret=top;
    for(int i=head[x];i;i=edge[i].next){
        int to=edge[i].to;
        if(to==fa)    continue;
        dfs(to,x);
        s[x]+=2+s[to];
        sta[++top]=to;
    }
    if(x^1)    f[x]=q[x]-s[x];
    int now=s[x];
    sort(sta+ret+1,sta+top+1,cmp);
    for(int i=ret+1;i<=top;++i){
        int to=sta[i];
        now-=s[to]+2;
        f[x]=max(f[x],f[to]-now-1);
    }
    f[x]=max(f[x],0LL);
    top=ret;
}

int main(){
    int n=read();
    for(int i=1;i<=n;++i)    q[i]=read();
    for(int i=1;i<n;++i){
        int from=read(),to=read();
        add(from,to);
        add(to,from);
    }
    dfs(1,1);
    printf("%lld\n",max(f[1],q[1])+n*2-2);
    return 0;
}

 

【Luogu】P3574FAR_FarmCraft(树形贪心)

标签:show   getch   htm   craft   str   include   algorithm   题目   class   

原文地址:https://www.cnblogs.com/cellular-automaton/p/8351126.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!