poj1470 LCA Tarjan
比较直接的题目,入门一下。
#include<map> #include<queue> #include<stack> #include<cmath> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define INF 99999999 #define ll __int64 #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 using namespace std; const int MAXN = 1010; struct node { int to; int v; int next; }edge[MAXN*3]; int pre[MAXN],ind,vis[MAXN],n,in[MAXN],acancestor[MAXN],ans[MAXN],pa[MAXN]; int query[MAXN][MAXN]; void add(int x,int y) { edge[ind].to = y; edge[ind].next = pre[x]; pre[x] = ind++; } int find(int x) { if(x != pa[x]) pa[x] = find(pa[x]); return pa[x]; } void dfs(int rt) { vis[rt] = 1; acancestor[rt] = rt; for(int i=pre[rt]; i!=-1; i=edge[i].next){ int t = edge[i].to; if(!vis[t]){ dfs(t); int fx = find(rt); int fy = find(t); if(fx != fy){ pa[fy] =fx; acancestor[fx] = rt; } } } for(int i=1; i<=n; i++){ if(vis[i] && query[rt][i]){ ans[acancestor[find(i)]]+=query[rt][i]; query[rt][i] = query[i][rt] = 0; } } } int main() { int i,j,root; while(scanf("%d",&n)!=EOF) { memset(query,0,sizeof(query)); for(i=1; i<=n; i++){ pa[i] = i; in[i] = 0; } ind = 1; memset(pre,-1,sizeof(pre)); for(i=1; i<=n; i++){ int u,v,t; scanf("%d:(%d)",&u,&t); while(t--) { scanf("%d",&v); add(u,v); add(v,u); in[v] ++; } } int m; scanf("%d",&m); int x,y; while(m--) { char c; cin>>c; scanf("%d %d)",&x,&y); query[x][y]++; query[y][x]++; } memset(acancestor,0,sizeof(acancestor)); memset(vis,0,sizeof(vis)); memset(ans,0,sizeof(ans)); for(i=1; i<=n; i++){ if(in[i] == 0){ root = i; break; } } dfs(root); for(i=1; i<=n; i++){ if(ans[i] > 0){ printf("%d:%d\n",i,ans[i]); } } } return 0; }