The K-th Distance
Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 202 Accepted Submission(s): 50
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
Source
BestCoder Round #17
给定一个n个节点的树,求路径长度前k大的所有路径和。
题解方法:把所有边(u,v) 以及(v,u)放入一个队列,队列每弹出一个元素(u,v),对于所有与u相邻的点w,如果w!=v,就把(w,u)入队。这样就能一个一个生成前K小的距离。注意到每条边实际上会入队两次,只要把K翻倍且把ans除2即可,时间复杂度为O(n+K)
由于思路简单,就懒得写代码了,直接抄了yyn代码:
#include
还有一种方法,按照树分治考虑,由于k最大为1000000,那么第k长的路径长度必然数据不是很大,我们可以估计一个上限,然后按照树分治的做法,统计每一个长度的方案数,对于每一个分治重心,枚举每一颗子树,然后统计方案数,最后扫描一遍就行了。
代码:
/* ***********************************************
Author :rabbit
Created Time :2014/11/9 12:03:22
File Name :H.cpp
************************************************ */
#pragma comment(linker, "/STACK:102400000,102400000")
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include