自用lca模板

人丑常数大,总是卡在1000多ms。。。

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 #define maxn 5000005
 5 #define jump_max 19
 6 struct Edge{
 7     int from,to;
 8 };
 9 Edge edge[maxn];
10 int n,m,s,x,y,a,b;
11 int dep[maxn];
12 int f[maxn][20];
13 int head[maxn];
14 int tot = 0;
15 inline void swap_ele(int &a,int &b){
16     int c = a;
17     a = b;
18     b = c;
19 }
20 inline int read(){
21     int num = 0;
22     char c;
23     bool flag = false;
24     while ((c = getchar()) == ' ' || c == '\n' || c == '\r');
25     if (c == '-')
26         flag = true;
27     else
28         num = c - '0';
29     while (isdigit(c = getchar()))
30         num = num * 10 + c - '0';
31     return (flag ? -1 : 1) * num;
32 }
33 void add_edge(int from,int to){
34     edge[++tot].from = head[from];
35     edge[tot].to = to;
36     head[from] = tot;
37 }
38 void dfs(int step){
39     for (int i=head[step];i!=0;i = edge[i].from){
40         int v = edge[i].to;
41         if (dep[v] == 0){
42             dep[v] = dep[step] + 1;
43             f[v][0] = step;
44             dfs(v);
45         }
46     }
47 }
48 void init(){
49 
50     for (register int i=1;i<=jump_max;i++)
51         for (register int j=1;j<=n;j++)
52             f[j][i] = f[ f[j][i-1] ][ i-1 ];
53 }
54 
55 int lca(int x,int y){
56     if (dep[x] < dep[y])
57         swap_ele(x,y);
58     for (register int i=jump_max;i>=0;--i){
59         if (dep[f[x][i]] >= dep[y])
60             x = f[x][i];
61     }
62     if (x == y)
63         return y;
64     for (register int i=jump_max;i>=0;--i)
65         if (f[x][i] != f[y][i]){
66             x = f[x][i];
67             y = f[y][i];
68         }
69         
70     return f[x][0];
71 }
72 
73 int main(){
74     n = read();m = read();s = read();
75     for (register int i=1;i<=n-1;++i){
76         x = read();y = read();
77         add_edge(x,y);add_edge(y,x);
78     }
79     dep[s] = 1;
80     dfs(s);
81     init();
82     for (register int i=1;i<=m;++i){
83         a = read();b = read();
84         printf("%d\n",lca(a,b));
85     }
86     return 0;
87 }

 

posted @ 2017-10-06 23:39  ShawnZhou_Aether  阅读(177)  评论(0编辑  收藏  举报