贪心,树形结构

题目:https://codeforces.ml/contest/1337/problem/C

#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
typedef long long ll;
#define all(x) x.begin() x.end()
const ll maxn = 2e5 + 10;
vector<ll>G[maxn];
ll node[maxn];
vector<ll>happy;
ll n, k;
bool cmp(ll a, ll b)
{
    return a > b;
}
void dfs(ll u, ll f, ll len)
{
    for (auto v : G[u])//从当前结点出发
    {
        if (v != f) { dfs(v, u, len + 1), node[u] += node[v];}//将其子节点进行搜索
        //node计算后继节点
    }
    happy.push_back(len - node[u]);//路径长减去后继等于贡献值
    node[u]++;
}
int main()
{
    for (int i = 0; i < maxn; i++)
    {
        for (int j = 0; j < G[i].size(); j++)
        {
            G[i][j] = 0;
        }
    }
    for (int i = 0; i < happy.size(); i++)
    {
        happy[i] = 0;
    }
    memset(node, 0, sizeof(node));
    cin >> n >> k;
    for (int i = 0; i < n - 1; i++)
    {
        ll x, y;
        cin >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    dfs(1, 0, 0);//从1节点开始进行搜索
    sort(happy.begin(), happy.end(), cmp);
    ll sum = 0;
    for (int i = 0; i < k; i++)
    {
        sum += happy[i];
    }
    cout << sum << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值