Poj1470 Closest Common Ancestors LCA
2014-11-08 16:12
337 查看
LCA裸题。。
#include<iostream> #include<cstdio> #include<cstring> #include<map> #include<vector> using namespace std; const int maxn = 1111; int head[maxn]; int len; struct Node { int to; int next; }e[maxn * 2]; int father[maxn]; int color[maxn]; int vis[maxn]; int gg[maxn]; vector <int> q[maxn]; void add(int from, int to) { e[len].to = to; e[len].next = head[from]; head[from] = len++; } int getfather(int x) { if (father[x] != x) father[x] = getfather(father[x]); return father[x]; } void un(int a, int b) { int fa = getfather(a); int fb = getfather(b); father[fb] = fa; } void dfs(int x) { for (int i = head[x]; ~i; i = e[i].next){ int cc = e[i].to; dfs(cc); un(x, cc); } color[x] = 1; for (int i = 0; i <q[x].size(); i++){ int t = q[x][i]; if (color[t]){ int t1 = getfather(q[x][i]); vis[t1]++; } } } void init(int n) { len = 0; memset(head, -1, sizeof(head)); for (int i = 1; i <= n; i++) father[i] = i; memset(head, -1, sizeof(head)); for (int i = 1; i <= n; i++) q[i].clear(); memset(color, 0, sizeof(color)); for (int i = 1; i <= n; i++) vis[i] = 0; for (int i = 1; i <= n; i++) gg[i] = 0; } int main() { int n; while (cin >> n){ init(n); int m, a, b, c; for (int i = 0; i<n; i++){ scanf("%d", &a); scanf(":(%d)", &b); for (int j = 0; j<b; j++){ scanf("%d", &c); add(a, c); gg[c] = 1; } } scanf("%d", &m); while (m--){ scanf(" (%d %d)", &a, &b); // printf("%d %djiji\n",a,b); q[a].push_back(b); q[b].push_back(a); } int root; for (int i = 1; i <= n; i++) if (!gg[i]){ root = i; break; } dfs(root); for (int i = 1; i <= n; i++){ if (vis[i]){ printf("%d:%d\n", i, vis[i]); } } } return 0; }
相关文章推荐
- poj1470-Closest Common Ancestors(LCA)
- POJ-1470 Closest Common Ancestors Tarjan-LCA
- poj--1470--Closest Common Ancestors--LCA
- poj 1470 Closest Common Ancestors 【并查集 求根 + 求解每一个节点是多少对(a,b)的LCA】
- POJ 1470 Closest Common Ancestors (LCA)
- poj 1470 Closest Common Ancestors (离线LCA Tarjan)
- POJ 1470 Closest Common Ancestors 离线LCA
- POJ 1470 Closest Common Ancestors (LCA)
- POJ - 1470 Closest Common Ancestors(LCA离线)
- poj 1470 Closest Common Ancestors(LCA)
- poj1470 Closest Common Ancestors LCA(最近公共祖先)
- Closest Common Ancestors【POJ1470】——LCA
- Poj 1470 Closest Common Ancestors(Tarjin 求LCA)
- POJ 1470 Closest Common Ancestors (LCA, dfs+ST在线算法)
- POJ1470 Closest Common Ancestors(最近公共祖先lca,离线Tarjan)
- poj 1470 Closest Common Ancestors(LCA)
- POJ 1470 Closest Common Ancestors LCA_Tarjan
- poj 1470 Closest Common Ancestors(简单的LCA算法)
- POJ 1470 Closest Common Ancestors(离线tarjan-LCA)
- POJ 1470 Closest Common Ancestors (LCA,离线Tarjan算法)