题目链接:http://poj.org/problem?id=1330
题意就是求一组最近公共祖先,昨晚学了离线tarjan,今天来实现一下。
个人感觉tarjan算法是利用了dfs序和节点深度的关系,大致的意思:dfs如果不递归到递归基,那么dfs就会越递归越深,这个时候深度也是相应增加的,所以这个时候任意在已经遍历过的节点中选取两个点,计算他们的lca也就相当于是用并查集求他们的root。而dfs执行到递归基,转而执行下一个分支的时候,这个时候dfs的节点应当是小于等于之前执行到递归基的节点(叶节点)的深度的,此时再更新并查集那就自然不是和之前比此节点深度更深的节点的root了,因为那些root有可能比此点更低。
1 /* 2 ━━━━━┒ギリギリ♂ eye! 3 ┓┏┓┏┓┃キリキリ♂ mind! 4 ┛┗┛┗┛┃\○/ 5 ┓┏┓┏┓┃ / 6 ┛┗┛┗┛┃ノ) 7 ┓┏┓┏┓┃ 8 ┛┗┛┗┛┃ 9 ┓┏┓┏┓┃ 10 ┛┗┛┗┛┃ 11 ┓┏┓┏┓┃ 12 ┛┗┛┗┛┃ 13 ┓┏┓┏┓┃ 14 ┃┃┃┃┃┃ 15 ┻┻┻┻┻┻ 16 */ 17 #include <algorithm> 18 #include <iostream> 19 #include <iomanip> 20 #include <cstring> 21 #include <climits> 22 #include <complex> 23 #include <fstream> 24 #include <cassert> 25 #include <cstdio> 26 #include <bitset> 27 #include <vector> 28 #include <deque> 29 #include <queue> 30 #include <stack> 31 #include <ctime> 32 #include <set> 33 #include <map> 34 #include <cmath> 35 36 using namespace std; 37 38 #define fr first 39 #define sc second 40 #define cl clear 41 #define BUG puts("here!!!") 42 #define W(a) while(a--) 43 #define pb(a) push_back(a) 44 #define Rint(a) scanf("%d", &a) 45 #define Rll(a) scanf("%lld", &a) 46 #define Rs(a) scanf("%s", a) 47 #define Cin(a) cin >> a 48 #define FRead() freopen("in", "r", stdin) 49 #define FWrite() freopen("out", "w", stdout) 50 #define Rep(i, len) for(int i = 0; i < (len); i++) 51 #define For(i, a, len) for(int i = (a); i < (len); i++) 52 #define Cls(a) memset((a), 0, sizeof(a)) 53 #define Clr(a, x) memset((a), (x), sizeof(a)) 54 #define Full(a) memset((a), 0x7f7f, sizeof(a)) 55 #define lrt rt << 1 56 #define rrt rt << 1 | 1 57 #define pi 3.14159265359 58 #define RT return 59 typedef long long LL; 60 typedef long double LD; 61 typedef unsigned long long ULL; 62 typedef pair<int, int> pii; 63 typedef pair<string, int> psi; 64 typedef map<string, int> msi; 65 typedef vector<LL> vl; 66 typedef vector<vl> vvl; 67 typedef vector<bool> vb; 68 69 const int maxn = 10010; 70 int n, in[maxn]; 71 vector<int> G[maxn]; 72 int pre[maxn]; 73 bool vis[maxn]; 74 int u, v; 75 76 int find(int x) { 77 return x == pre[x] ? x : pre[x] = find(pre[x]); 78 } 79 80 void unite(int x, int y) { 81 x = find(x); y = find(y); 82 if(x != y) pre[y] = x; 83 } 84 85 void dfs(int u) { 86 pre[u] = u; 87 Rep(i, G[u].size()) { 88 if(!vis[G[u][i]]) { 89 dfs(G[u][i]); 90 unite(u, G[u][i]); 91 } 92 } 93 vis[u] = 1; 94 if(u == ::u && vis[::v]) printf("%d ", find(::v)); 95 if(u == ::v && vis[::u]) printf("%d ", find(::u)); 96 } 97 98 int main() { 99 // FRead(); 100 int T; 101 Rint(T); 102 W(T) { 103 Cls(in); Cls(vis); 104 Rep(i, maxn) G[i].clear(); 105 Rint(n); 106 Rep(i, n-1) { 107 Rint(u); Rint(v); 108 G[u].push_back(v); in[v]++; 109 } 110 Rint(u); Rint(v); 111 For(i, 1, n+1) if(!in[i]) dfs(i); 112 } 113 RT 0; 114 }