标签:des style blog http color os io ar strong
Time Limit: 2000MS | Memory Limit: 10000K | |
Total Submissions: 15446 | Accepted: 4944 |
Description
Input
Output
Sample Input
5 5:(3) 1 4 2 1:(0) 4:(0) 2:(1) 3 3:(0) 6 (1 5) (1 4) (4 2) (2 3) (1 3) (4 3)
Sample Output
2:1 5:5
Hint
Source
1 /*poj 1470*/ 2 #include<iostream> 3 #include<vector> 4 #include<cstdio> 5 #include<cstring> 6 #include<cstdlib> 7 using namespace std; 8 const int maxn=902; 9 vector<int> tree[maxn],qus[maxn]; 10 int rank[maxn],father[maxn]; 11 bool vis[maxn]; 12 int rudu[maxn]; 13 int lroot[maxn]; 14 int ans[maxn]; 15 16 void init(int n){ 17 memset(vis,0,sizeof(char)*(n+1)); 18 memset(rudu,0,sizeof(int)*(n+1)); 19 memset(lroot,0,sizeof(int)*(n+1)); 20 memset(ans,0,sizeof(int)*(n+1)); 21 for(int i=1;i<=n;i++){ 22 father[i]=i; 23 rank[i]=1; 24 tree[i].clear(); 25 qus[i].clear(); 26 } 27 } 28 29 int find(int a){ 30 while(a!=father[a]) 31 a=father[a]; 32 return a; 33 } 34 35 void Union(int a,int b) 36 { 37 int x=find(a); 38 int y=find(b); 39 if(x==y) return ; 40 if(rank[x]<rank[y]){ 41 rank[y]+=rank[x]; 42 father[x]=y; 43 } 44 else { 45 rank[x]+=rank[y]; 46 father[y]=x; 47 } 48 } 49 50 void LCA(int u) 51 { 52 lroot[u]=u; 53 //vis[u]=1; 不能放在这里 54 int len=tree[u].size(); 55 for(int i=0;i<len;i++){ 56 LCA(tree[u][i]); 57 Union(u,tree[u][i]); 58 lroot[find(u)]=u; 59 } 60 vis[u]=1; 61 int ss=qus[u].size(); 62 for(int i=0;i<ss;i++){ 63 if(vis[qus[u][i]]){ 64 ans[lroot[find(qus[u][i])]]++; 65 //return ; 66 } 67 } 68 } 69 70 int main() 71 { 72 int n,m,t,u1,u2; 73 freopen("test.in","r",stdin); 74 while(scanf("%d",&n)!=EOF){ 75 init(n); 76 for(int i=0;i<n;i++){ 77 getchar(); 78 scanf("%d:(%d))",&u1,&m); 79 for(int j=0;j<m;j++){ 80 scanf("%d",&u2); 81 tree[u1].push_back(u2); 82 rudu[u2]++; 83 } 84 } 85 scanf("%d",&t); 86 for(int i=0;i<t;i++) 87 { 88 scanf("%*1s%d%d%*1s",&u1,&u2); 89 qus[u1].push_back(u2); 90 qus[u2].push_back(u1); 91 } 92 for(int i=1;i<=n;i++) 93 { 94 if(rudu[i]==0) 95 { 96 LCA(i); 97 break; 98 } 99 } 100 for(int i=1;i<=n;i++){ 101 if(0!=ans[i]) 102 printf("%d:%d\n",i,ans[i]); 103 } 104 } 105 return 0; 106 }
poj----(1470)Closest Common Ancestors(LCA)
标签:des style blog http color os io ar strong
原文地址:http://www.cnblogs.com/gongxijun/p/3957223.html