您的位置:首页 > 产品设计 > UI/UE

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 iterator struct c