Codeforces Round #646 (Div. 2)E. Tree Shuffling 题解(dfs)

题目链接

题目大意

给你一颗树,每一个节点有一个a[i],b[i],c[i]值,你要把b[i]变成c[i],b[i]和c[i]为[0,1],你操作的方法是,选择一个节点x,选择他的k个子树,然后进行交换他们的b[i]值,使满足要求,每次操作的cost为a[x]*k,求满足题目要求所需要的最小cost,如果不能满足要求,则输出-1.

题目思路

基本思路想到了,但是不会实现,码力太差,直接放标准解析。

Key Idea: Let the parent of node i be p. If a[i]≥a[p], we can do the shuffling which was done at i, at p instead. Thus, we can do the operation a[i]=min(a[i],a[p]).

Detailed Explanation: Let us denote nodes that have bi=1 and ci=0 as type 1, and those that have bi=0 and ci=1 as type 2. Firstly, the answer is −1 if and only if the number of nodes of type 1 and type 2 are unequal.

We also observe that only nodes of type 1 and 2 should be shuffled - it is unoptimal to shuffle those which already have b[i]=c[i]. Thus, we should try to exchange the values of type 1 and type 2 nodes.

We use the key idea by going down from the root, and at every node i, setting a[i]=min(a[i],a[p]) where p is the parent node of i in the tree. Thus, the a[i]'s now follow a special structure: they are non-increasing from the root to the leaves!

This paves the way for our greedy solution: we will go upwards from the leaves, and at each node i interchange type 1 and type 2 nodes until we have no nodes in one of these types. Then, we pass on the remaining nodes to the parent to be shuffled.

代码

#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=2e5+5;
int n,a[maxn],b[maxn],c[maxn],head[maxn],cnt;
ll cost;
struct node{
    int to,next;
}e[maxn<<1];
void add(int u,int v){
    e[++cnt].to=v;
    e[cnt].next=head[u];
    head[u]=cnt;
}
pair<int,int> dfs(int son,int fa,int mi){
    pair<int,int> x;
    x.first=x.second=0;
    if(b[son]==1&&c[son]==0){
        x.first++;
    }else if(b[son]==0&&c[son]==1){
        x.second++;
    }
    for(int i=head[son];i;i=e[i].next){
        if(e[i].to!=fa){
            pair<int,int> y=dfs(e[i].to,son,min(mi,a[son]));
            x.first+=y.first;
            x.second+=y.second;
        }
    }
    if(a[son]<=mi){
        int take=min(x.first,x.second);
        cost+=1ll*2*take*a[son];
        x.first-=take;
        x.second-=take;
    }
    return x;
}
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d %d %d",&a[i],&b[i],&c[i]);
    }
    for(int i=1,u,v;i<=n-1;i++){
        scanf("%d %d",&u,&v);
        add(u,v),add(v,u);
    }
    pair<int,int> ans=dfs(1,1,a[1]);
    if(ans.first==0&&ans.second==0){
        printf("%lld\n",cost);
    }else{
        printf("-1\n");
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值