Linova and Kingdom

C - Linova and Kingdom

Reference: Codeforces Round # 635 Editorial

The first rule to know is that if a city is an industrial city, then all its child nodes must also be industrial cities. It can be proved by the counter-evidence law.

Then we can get the contribution of each tourist city as (subtree size-node depth), and the proof method can be viewed in the official solution.

If there is no idea, you can first deduce the rules, and then solve according to the obtained rules. If you can turn the analysis of the entire graph into an independent analysis of a point, then it is very easy.

// Created by CAD on 2020/4/17.
#include <bits/stdc++.h>

#define ll long long
using namespace std;

const int maxn=2e5+5;
vector<int> g[maxn];
int son[maxn],d[maxn];
void dfs(int x,int fa,int deep){
    son[x]=1;
    for(auto i:g[x])
        if(i!=fa) dfs(i,x,deep+1),son[x]+=son[i];
    d[x]=son[x]-deep;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n,k;    cin>>n>>k;
    for(int i=1,x,y;i<=n-1;++i)
        cin>>x>>y,g[x].push_back(y),g[y].push_back(x);
    dfs(1,0,1);
    sort(d+1,d+n+1,greater<int>());
    ll sum=0;
    for(int i=1;i<=n-k;++i) sum+=d[i];
    cout<<sum<<"\n";
    return 0;
}

Guess you like

Origin www.cnblogs.com/CADCADCAD/p/12719936.html