首页 > 代码库 > Poj1470 Closest Common Ancestors LCA
Poj1470 Closest Common Ancestors LCA
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。