HDU-5102-The K-th Distance【思维】【好题】

86 篇文章 9 订阅
17 篇文章 0 订阅

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值