Codeforces Round 646 E

codeforces round 646 E

题目

在这里插入图片描述

题目大意

有一个树,每一个节点有一个数字0或着1,要改变一个节点或者其子树的值,改动一个需要ai的代价,问改称目的状态需要最小的代价是多少

思路

首先,我们可以贪心的求一下,每一个节点最小改动价值,若节点i的父亲是j,那么对于i节点来说,a[i] = min (a[i], a[j]), dfs改动一轮之后,记录每一个点的0->1和1->0的有多少对,改动一下记录价值,回溯一下就行了

代码

#include <iostream>
#include <cstdio>
#include <set>
#include <list>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <string>
#include <sstream>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <fstream>
#include <iomanip>
//#include <unordered_map>
using namespace std;
#define dbg(x) cerr << #x " = " << x << endl;
typedef pair<int, int> P;
typedef long long ll;
#define FIN freopen("in.txt", "r", stdin);
const int MAXN = 2e5 + 5;
vector<int> v[MAXN];
ll a[MAXN], b[MAXN], c[MAXN];
int vis[MAXN];
ll ans = 0;
P dfs(int u, int fa, ll w)
{
    P aa = P(0 ,0);
    if(b[u] != c[u])
    {
        if(b[u])
        {
            aa.first++;
        }
        else
        {
            aa.second++;
        }
    }
    for (int i = 0; i < v[u].size(); i++)
    {
        int next = v[u][i];
        if(next == fa) continue;
        P tmp = dfs(next, u, min(a[u], w));
        aa.first += tmp.first;
        aa.second += tmp.second;
    }
    if(a[u] < w)
    {
        ll take = min(aa.first, aa.second);
        ans += take * a[u] * 2;
        aa.first -= take;
        aa.second -= take;
    }
    return aa;
}
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int n;
    cin >> n;
    int flg = 0;
    for (int i = 1; i <= n; i++)
    {
        cin >> a[i] >> b[i] >> c[i];
        flg += b[i] - c[i];
    }
    for (int i = 0; i < n - 1; i++)
    {
        int st, ed;
        cin >> st >> ed;
        v[st].push_back(ed);
        v[ed].push_back(st);
    }
    if (flg)
        cout << "-1" << endl;
    else
    {
        dfs(1, 0, 2e9);
        cout << ans << endl;
    }
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值