Problem Description
Given a tree, which has n node in total. Define the distance between two node u and v is the number of edge on their unique route. So we can have n(n-1)/2 numbers for all the distance, then sort the numbers in ascending order. The task is to output the sum of the first K numbers.
Input
There are several cases, first is the number of cases T. (There are most twenty cases).
For each case, the first line contain two integer n and K (2≤n≤100000,0≤K≤min(n(n−1)/2,106) ). In following there are n-1 lines. Each line has two integer u , v. indicate that there is an edge between node u and v.
Output
For each case output the answer.
Sample Input
2
3 3
1 2
2 3
5 7
1 2
1 3
2 4
2 5
Sample Output
4
10
题目链接:HDU-5102
题目大意:给出一棵树,每条边的权值为1,将树上所有两点之间的距离存进数组,进行从小到大排序,问前k个的值为多少。
题目思路:因为k的范围为10^6,所以可以从这里入手。
用一个队列,q:
u,v: 左边界限,右边界限
w: 层数(左界限到右界限的距离)
因为得到的数组是从小到大排序,所以我们可以考虑,处理所有长度为1的,然后将左界限和右界限进行扩展一格,处理长度为2的。以此。
注意:刚开始,我为了处理该左界限和右界限是否被计算过,使用了map来存,MLE了。
实际上,计算时,每个值重复两次,所以答案/2就可以了,不需要使用map来标记
参考博客:here
以下是代码:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <functional>
#include <numeric>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <queue>
#include <deque>
#include <list>
typedef long long ll;
using namespace std;
#define maxn 100001
vector <int> vec[maxn];
struct node
{
int u,v,w;
node(int u,int v,int w):u(u),v(v),w(w){}
};
queue<node> q;
map<long long, bool> mp;
int main()
{
int _;
cin >> _;
while(_--)
{
while(!q.empty()) q.pop();
for (int i = 0; i < maxn; i++) vec[i].clear();
int n,k;
cin >> n >> k;
k *= 2;
for (int i = 0; i < n - 1; i++)
{
int u,v;
cin >> u >> v;
vec[u].push_back(v);
vec[v].push_back(u);
}
for (int i = 1; i <= n; i++)
{
q.push(node(i,i,0));
}
int cnt = 0;
long long ans = 0;
while(!q.empty())
{
node front = q.front();
q.pop();
if (cnt >= k) break;
int u = front.u;
int w = front.w;
for (int i = 0; i < vec[u].size(); i++)
{
int v = vec[u][i];
if (v == front.v) continue;
if (cnt < k)
{
cnt++;
ans += w + 1;
q.push(node(v,u,w + 1));
}
}
}
cout << ans / 2 << endl;
}
return 0;
}