PKU 1986 Distance Queries LCA
2009-10-07 15:10
344 查看
经典的LCA问题
#include <iostream> #include <vector> #include <cstdio> using namespace std; const int NMAX = 40009; int N,M,K,i,j; int father[NMAX],rank[NMAX],dist[NMAX],Q[NMAX],ancestor[NMAX]; struct node { int u , v , dis ;}; struct node1{ int v , num ;}; vector<node> lca[NMAX]; vector<node1> Qes[NMAX]; bool used[NMAX],visit[NMAX]; void init() { for( i=1; i<=N; i++ ){ rank[i] = 1; father[i] = i; dist[i] = 0; Q[i] = 0; used[i] = false; ancestor[i] = 0; } } int find(int x) { if( father[x] != x ) return father[x] = find( father[x] ); return x; } void link( int x, int y ) { if( rank[x] > rank[y] ){ father[y] = x; } else { father[x] = y; if( rank[x] == rank[y] ) rank[y] ++; } } void LCA( int u , int dis ) //递归增加距离 { if( !used[u] ){
used[u] = true; dist[u] = dis; ancestor[u] = u; for( vector<node>::iterator it = lca[u].begin(); it != lca[u].end(); it++ ){ node temp = *it; < 4000 span class="sh_keyword">if( !used[temp.v] ){ LCA( temp.v , temp.dis + dis );//很好 link( find(u) , find(temp.v) ); ancestor[ find(u) ] = u;}//记录老祖宗 } visit[u] = true; for( vector<node1>::iterator it = Qes[u].begin(); it != Qes[u].end(); it++ ){ if( visit[ (*it).v ] ){ Q[ (*it).num ] = dist[ u ] + dist[ (*it).v ] - 2 * dist[ ancestor[ find( (*it).v ) ] ]; } } } } int main() { scanf( "%d %d", &N , &M ); init(); int s , t , root ; for( i=1; i<=M; i++ ){ char c; node temp; scanf( "%d %d %d %c", &temp.u, &temp.v , &temp.dis, &c ); if( i == 1 ) root = temp.u; lca[ temp.u ].push_back( temp ); swap( temp.u , temp.v ); lca[ temp.u ].push_back( temp ); } scanf( "%d", &K ); for( i=1; i<=K; i++ ){ scanf( "%d %d", &s, &t ); node1 temp ; temp.num = i; temp.v = t; Qes[s].push_back( temp ); temp.v = s; Qes[t].push_back( temp ); } LCA( root , 0 ); for( i=1; i<=K; i++ ){ printf( "%d/n", Q[i] ); }
return 0; }
相关文章推荐
- Distance Queries POJ - 1986 (LCA在线方法求解 公共祖先(带权值))
- POJ 1986 Distance Queries LCA
- POJ 1986 Distance Queries LCA树上两点的距离
- 1986 Distance Queries //LCA
- 1986 Distance Queries //LCA+VECTOR 贼慢
- POJ 1984 Distance Queries LCA
- POJ 1986 Distance Queries / UESTC 256 Distance Queries / CJOJ 1129 【USACO】距离咨询(最近公共祖先)
- poj 1968 Distance Queries LCA Tarjan 离线算法
- POJ 1986 Distance Queries && HDOJ 2586 How far away?
- pku 1986 LCA算法的应用
- 【RMQ&LCA】Distance Queries(距…
- poj 1986 Distance Queries(LCA:倍增/离线)
- poj 1986 RMQ&&LCA( 模板题)
- POJ 1986 Distance Queries [LCA]
- POJ 1986 Distance Queries (离线LCA)
- CS 400 Root LCA Queries 思维+LCA
- pku1330 LCA问题
- POJ 1986 Distance Queries(LCA)
- poj1986 Distance Queries(LCA)
- POJ 1986 裸的LCA