Codeforces Round #635 (Div. 2) C.Linova and Kingdom

Codeforces Round #635 (Div. 2) C.Linova and Kingdom

题目链接
Writing light novels is the most important thing in Linova’s life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.

在这里插入图片描述

There are n cities and n−1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.

As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.

A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).

Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.

In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?

Input

The first line contains two integers n and k (2≤n≤2⋅105, 1≤k<n) — the number of cities and industry cities respectively.

Each of the next n−1 lines contains two integers u and v (1≤u,v≤n), denoting there is a road connecting city u and city v.

It is guaranteed that from any city, you can reach any other city by the roads.

Output

Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.

扫描二维码关注公众号,回复: 11128434 查看本文章

Examples

input

7 4
1 2
1 3
1 4
3 5
3 6
4 7

output

7

input

4 1
1 2
1 3
2 4

output

2

input

8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5

output

9

这题比较难想,直接判儿子的数量(此处的儿子是指当前结点下的所有子树的结点个数和)和深度都不对(别问,问就是我错了/(ㄒoㄒ)/~~),后来把这两者相减就写出来了,现在想想没问题,你求一个结点 p p 的快乐值,正好等于该结点的深度 d e p t h depth 减去该结点的儿子数量 s o n son ,AC代码如下:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e5+5;
vector<int>g[N];
struct node{
    int id;
    int son,depth;
}p[N];

void dfs(int u,int f){
    for(int v:g[u]){
        if(v==f) continue;
        p[v].depth=p[u].depth+1;
        dfs(v,u);
        p[u].son+=p[v].son+1;
    }
}

bool cmp(node a,node b){
    return a.depth-a.son>b.depth-b.son;
}

int main(){
    int n,k,u,v;
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++) p[i].id=i;
    for(int i=0;i<n-1;i++){
        scanf("%d%d",&u,&v);
        g[u].push_back(v);
        g[v].push_back(u);
    }
    p[1].depth=0;
    dfs(1,-1);
    sort(p+1,p+1+n,cmp);
    ll sum=0;
    for(int i=1;i<=k;i++){
       sum+=ll(p[i].depth-p[i].son);
    }
    cout<<sum<<endl;
}
发布了479 篇原创文章 · 获赞 38 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/qq_43765333/article/details/105552261