题目: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;
}