PKU 1986 Distance Queries LCA

来源:互联网 发布:农业科技网络书屋登录 编辑:程序博客网 时间:2024/05/21 14:07

经典的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;             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;}
原创粉丝点击