HDU5102(树的前k路径+队列)

The K-th Distance

Time Limit: 8000/4000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 332    Accepted Submission(s): 90


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 ( 2n100000,0Kmin(n(n1)/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
 

Source

题意:给出一棵树,边权为1,求前k长的路径和

思路:用一个队列维护即可,先将所有边入队,然后不停的用边的一个端点向外扩张,每扩张一次,路径长度就+1

            这样求出前k个即可

#include 
   
   
    
    
#include 
    
    
     
     
#include 
     
     
      
      
#include 
      
      
       
       
#include 
       
       
         #include 
        
          using namespace std; typedef __int64 ll; const int MAXN = (int)1e6+5; struct node{ int u,v,d; node(){} node(int a,int b,int c):u(a),v(b),d(c){} }q[MAXN<<1]; int front,rear; int head[MAXN]; int edge[MAXN<<1]; int next[MAXN<<1]; int esz; void addedge(int u,int v) { edge[esz]=v; next[esz]=head[u]; head[u]=esz++; } int main() { int t; scanf("%d",&t); while(t--){ int n,k; scanf("%d%d",&n,&k); front=rear=0; memset(head,-1,sizeof(head));esz=0; for(int i=1;i 
          
         
       
      
      
     
     
    
    
   
   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值