HDU 2586 How far away ?

时间:2019-09-25
本文章向大家介绍HDU 2586 How far away ?,主要包括HDU 2586 How far away ?使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2586

题目是说:N个顶点形成树,接下来有M次询问两个顶点间的距离~

解题思路:用Tarjan脱机最小公共祖先算法(
P319)

然后计算两个顶点到根部的距离加起来与他们公共祖先到根部的距离乘以2的绝对值

Dist(u,v) = abs(dist[u]+dist[v]-2*dist[ancestor[v]]);

Tarjan算法我是看着敲出来了,书上习题有几个证明自己还没去做,这两天感冒发烧,解释什么的先不写了,也写不来
(我觉得里面好像还很多问题)

晒一下我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104

#include <stdlib.h>
#include <string.h>
#include <math.h>
#define Maxn 40001
typedef struct
{
int NO_;
int D;
struct *NextChild;
}Node;
Node* FirstChild[Maxn];
int ancestor[Maxn];
int p[Maxn];
int rank[Maxn];
int dist[Maxn];
enum boolean{FALSE,TRUE};
enum COLOR{WHITE,BLACK};
unsigned char color[Maxn];
unsigned char Visit[Maxn];
void MAKE_SET(int x)
{
p[x] = x;
rank[x] = 0;
}
void LINK(int x,int y)
{
if (rank[x]>rank[y])
p[y] = x;
else
{
p[x] = y;
if (rank[x]==rank[y])
rank[y]++;
}
}
void UNION(int x,int y)
{
LINK(FIND_SET(x),FIND_SET(y));
}
int FIND_SET(x)
{
if ( x!=p[x] )
p[x] = FIND_SET(p[x]);
return p[x];
}
void LCA(int u)
{
if (Visit[u])
return;
Visit[u] = TRUE;
int v;
MAKE_SET(u);
ancestor[FIND_SET(u)] = u;
Node *p;
for (p = FirstChild[u]; p; p=p->NextChild)
{
v = p->NO_;
dist[v] = dist[u] + p->D;
LCA(v);
UNION(u,v);
ancestor[FIND_SET(u)] = u;
}
color[u] = BLACK;
}
int main()
{
freopen("Sample Input.txt","r",stdin);
int T;
int n,m;
int i,j,k;
int u,v,w;
Node *p;
scanf("%d",&T);
while (T--)
{
scanf("%d%d",&n,&m);
memset(FirstChild,NULL,sizeof(FirstChild));
memset(Visit,FALSE,sizeof(Visit));
memset(dist,0,sizeof(dist));
for (i = 1; i <= n-1; i++)
{
scanf("%d%d%d",&u,&v,&w);
p = (Node*)malloc(sizeof(Node));
p->NO_ = v;
p->D = w;
p->NextChild = FirstChild[u];
FirstChild[u] = p;
p = (Node*)malloc(sizeof(Node));
p->NO_ = u;
p->D = w;
p->NextChild = FirstChild[v];
FirstChild[v] = p;
}
LCA(1);
for (i = 1; i <= m; i++)
{
scanf("%d%d",&u,&v);
printf("%dn",abs(dist[u]+dist[v]-2*dist[ancestor[v]]));
}
}
getch();
return 0;
}

原文:大专栏  HDU 2586 How far away ?


原文地址:https://www.cnblogs.com/chinatrump/p/11584402.html