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; }
时间: 2024-10-25 16:27:36