hdu 5102

The K-th Distance

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


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

BestCoder Round #17

/*把所有边(u,v) 以及(v,u)放入一个队列,队列每弹出一个元素(u,v),对于所有与v相邻的点w,如果w!=u,
就把(v,w)入队。这样就能一个一个生成前K小的距离。
注意到每条边实际上会入队两次,只要把K翻倍且把ans除2即可,时间复杂度为O(n+K)*/
#include<stdio.h>
#include<string.h>
#include<queue>
#define N 100005
using namespace std;
struct node
{
    int u,v,w,next;
}a,b,bian[N*2];
int e,head[N];
queue<node>q;
void add(int u,int v)
{
    bian[e].u=u;
    bian[e].v=v;
    bian[e].next=head[u];
    head[u]=e++;
}
int main()
{
    int t,n,k,i,num,v,u;
    __int64 sum;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&k); k*=2;
        memset(head,-1,sizeof(head));
        e=0;
        for(i=1;i<n;i++)
        {
            scanf("%d%d",&u,&v);
            add(u,v);
            add(v,u);
        }
        while(!q.empty())
            q.pop();
        for(i=1;i<=n;i++)
        {
            a.u=a.v=i;a.w=0;
            q.push(a);
        }
        num=0;sum=0;
        while(!q.empty()&&num<k)
        {
            b=q.front(); q.pop();
            for(i=head[b.v];i!=-1;i=bian[i].next)
            {
                v=bian[i].v;
                if(v!=b.u)
                {
                  a.u=b.v; a.v=v; a.w=b.w+1;
                  num++;
                  q.push(a);
                  sum+=a.w;
                 // printf("%I64d\n",sum);
                  if(num==k)
                    break;
                }
            }
        }
        printf("%I64d\n",sum/2);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值