hdu5102 单位边权树上的前k长路径和:队列技巧

单向拓展边orz题解==

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<algorithm>
 4 #include<queue>
 5 using namespace std;
 6 int next[200005],head[200005],point[200005],now;
 7 void add(int x,int y)
 8 {
 9     next[++now]=head[x];
10     head[x]=now;
11     point[now]=y;
12 }
13 struct dian{
14     int u,v,t;
15 };
16 queue<dian>q;
17 int main()
18 {
19     int T,n,k,i,x,y,cnt,ans,tmp;
20     dian n1,n2;
21     scanf("%d",&T);
22     while (T--)
23     {
24         while (!q.empty()) q.pop();
25         memset(head,-1,sizeof(head));
26         scanf("%d%d",&n,&k);
27         now=0; k*=2;
28         for (i=1;i<n;i++)
29         {
30             scanf("%d%d",&x,&y);
31             add(x,y); add(y,x);
32             n1.u=x; n1.v=y; n1.t=1; q.push(n1);
33             n1.u=y; n1.v=x; n1.t=1; q.push(n1);
34         }
35         cnt=0; ans=0;
36         if (k==0) {printf("0\n"); continue;}
37         while (!q.empty())
38         {
39             n1=q.front(); q.pop();
40             cnt++; ans+=n1.t;
41             if (cnt==k) break;
42             tmp=cnt+q.size();
43             for (i=head[n1.v];i!=-1&&tmp<=k;i=next[i])
44             {
45                 x=point[i];
46                 if (x==n1.u) continue;
47                 n2.u=n1.v; n2.v=x; n2.t=n1.t+1;
48                 q.push(n2); tmp++;
49             }
50         }
51         printf("%d\n",ans/2);
52     }
53 }
View Code

http://acm.hdu.edu.cn/showproblem.php?pid=5102

posted on 2014-11-09 00:14  xiao_xin  阅读(221)  评论(0编辑  收藏  举报

导航