日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

hdu 2586 How far away ?

發布時間:2024/9/20 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 hdu 2586 How far away ? 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

最近公共祖先問題~~

題目大意:一個村子里有n個房子,這n個房子用n-1條路連接起來,接下了有m次詢問,每次詢問兩個房子a,b之間的距離是多少。

很明顯的最近公共祖先問題,先建一棵樹,然后求出每一點i到樹根的距離dis[i],然后每次詢問a,b之間的距離=dis[a]+dis[b]-2*dis[LCA(a,b)];

LCA(a,b)即是a,b的最近公共祖先。。

關于最近公共祖先,給大家推薦一個我學長的博客http://www.cnblogs.com/ylfdrib/archive/2010/11/03/1867901.html,里面講的很不錯!!

直接貼一下代碼:

View Code 1 # include<stdio.h>
2 # include<string.h>
3 # define N 40005
4 # define M 205
5 struct node{
6 int from,to,next,val;
7 }edge[2*N];
8 struct node1{
9 int from,to,next,num;
10 }edge1[2*M];
11 int tol,head[N],head1[N],tol1,father[N],dis[N],LCA[M],n,m;
12 bool visit[N];
13 void add(int a,int b,int c)
14 {
15 edge[tol].from=a;edge[tol].to=b;edge[tol].next=head[a];edge[tol].val=c;head[a]=tol++;
16 }
17 void add1(int a,int b,int c)
18 {
19 edge1[tol1].from=a;edge1[tol1].to=b;edge1[tol1].next=head1[a];edge1[tol1].num=c;head1[a]=tol1++;
20 }
21 int find(int x)
22 {
23 if(x!=father[x])
24 father[x]=find(father[x]);
25 return father[x];
26 }
27 void tarjan(int u)
28 {
29 int j,v;
30 visit[u]=1;
31 father[u]=u;
32 //
33 for(j=head1[u];j!=-1;j=edge1[j].next)
34 {
35 v=edge1[j].to;
36 if(visit[v]) LCA[edge1[j].num]=find(v);
37 }
38 //
39 for(j=head[u];j!=-1;j=edge[j].next)
40 {
41 v=edge[j].to;
42 if(!visit[v])
43 {
44 dis[v]=dis[u]+edge[j].val;
45 tarjan(v);
46 father[v]=u;
47 }
48 }
49 }
50 int main()
51 {
52 int i,ncase,a,b,c;
53 scanf("%d",&ncase);
54 while(ncase--)
55 {
56 scanf("%d%d",&n,&m);
57 tol=0;
58 memset(head,-1,sizeof(head));
59 for(i=1;i<n;i++)
60 {
61 scanf("%d%d%d",&a,&b,&c);
62 add(a,b,c);
63 add(b,a,c);
64 }
65 memset(visit,0,sizeof(visit));
66 tol1=0;
67 memset(head1,-1,sizeof(head1));
68 for(i=1;i<=m;i++)
69 {
70 scanf("%d%d",&a,&b);
71 add1(a,b,i);
72 add1(b,a,i);
73 }
74 ///LCA是一種離線算法,所以剛開始需要把所有的詢問都輸入,然后用鄰接表進行存儲,i表示第i次詢問
75 dis[1]=0;
76 tarjan(1);
77 for(i=0;i<tol1;i+=2)
78 {
79 a=edge1[i].from;
80 b=edge1[i].to;
81 c=edge1[i].num;
82 printf("%d\n",dis[a]+dis[b]-2*dis[LCA[c]]);
83 }
84 }
85 return 0;
86 }

轉載于:https://www.cnblogs.com/183zyz/archive/2011/08/03/2126589.html

總結

以上是生活随笔為你收集整理的hdu 2586 How far away ?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。