LCA Tarjan模板 HDU2586

来源:互联网 发布:2016淘宝打假新规则 编辑:程序博客网 时间:2024/05/18 18:17
#include <cstdio>#include <iostream>#include <algorithm>#include <vector>using namespace std;const int maxn = 40005;typedef long long ll;int Par[maxn], vis[maxn], dist[maxn];vector<int> G[maxn];vector<int> Dis[maxn];vector<int> Gx[maxn];vector<int> Gxnum[maxn];int getPar (int x) {    int r = x, i = x;    while(r != Par[r])        r = Par[r];    while(i != r) {        int tmp = Par[i];        Par[i] = r;        i = tmp;    }    return r;}void merge (int t1, int t2) {    int f1 = getPar(t1);    int f2 = getPar(t2);    if(f1 != f2)        Par[f2] = f1;}struct node {    int x, y, zx;} nod[205];void dfs (int st) {    for(int i=0; i<G[st].size(); ++i) {        if(!vis[G[st][i]]) {            vis[G[st][i]] = 1;            dist[G[st][i]] = dist[st] + Dis[st][i];            dfs(G[st][i]);            merge(st, G[st][i]);        }    }    for(int i=0; i<Gx[st].size(); ++i) {        if(vis[Gx[st][i]])            nod[Gxnum[st][i]].zx = getPar(Gx[st][i]);    }}int main (void) {    ios::sync_with_stdio(false);    int T, n, m, a, b, c;    cin>>T;    while(T --) {        for(int i=0; i<maxn; ++i) {            Par[i] = i, vis[i] = dist[i] = 0;            G[i].clear(), Dis[i].clear();            Gxnum[i].clear(), Gx[i].clear();        }        cin>>n>>m;        for(int i=1; i<n; ++i) {            cin>>a>>b>>c;            G[a].push_back(b);            Dis[a].push_back(c);            G[b].push_back(a);            Dis[b].push_back(c);        }        for(int i=1; i<=m; ++i) {            cin>>a>>b;            Gx[a].push_back(b);            Gx[b].push_back(a);            nod[i].x = a, nod[i].y = b;            Gxnum[a].push_back(i);            Gxnum[b].push_back(i);        }        vis[1] = 1; dfs(1);        for(int i=1; i<=m; ++i) {            int ans = dist[nod[i].x]+dist[nod[i].y]-2*dist[nod[i].zx];            cout<<ans<<endl;        }    }    return 0;} 
原创粉丝点击