[hdu 2586](LCA Tarjan算法)

算法参考:http://cache.baiducontent.com/c?m=9f65cb4a8c8507ed4fece763105392230e54f73c6f888b442282c45f93130a1c187bb8e7737f0704a5932b2152f4174bea863570330620b390df883d87fdcd763bcd7a742613913717c46ed8dc3653d654e14de8df0e97b1e741e3b9a2d8c82453dd52756df6f59c2d0403bb1be7653bf4a7e916440c07ba9c7636bf012475&p=806edf16d9c111a05bed94365a52bb&newp=c06cc116d9c113ed08e2977e0d4f97231610db2151d4d51e6b82c825d7331b001c3bbfb423231203d1c57d670bab485ee8f1337735092ba3dda5c91d9fb4c57479da65&user=baidu&fm=sc&query=%D7%EE%BD%FC%B9%AB%B9%B2%D7%E6%CF%C8LCA+Tarjan&qid=cc91b19e0004780c&p1=5

代码:

#include
#include
#include
using namespace std;
struct node{
    int x,y;
    node(int xx,int yy)
    {
        x=xx,y=yy;
    }node(){}
};
int ans[40005];
vector lin[40005];
vector q[40005];
int dis[40005];
int fa[40005];
int vis[40005];
int n,m,aa,bb,cc;

int find(int x)
{
    return x==fa[x]?x:fa[x]=find(fa[x]);
}
void unio(int x,int y)
{
    fa[find(y)]=find(x);
}

void init()
{
    for(int i=1;i<=n;i++)
    {
        lin[i].clear();
        q[i].clear();
        fa[i]=i;
        vis[i]=0;
        ans[i]=0;
        dis[i]=0;
    }
}
void dfs(int x)
{

    vis[x]=1;
    for(int i=0;ix].size();i++)
    {
        int v=lin[x][i].x;
        if(!vis[v])
        {
            dis[v]=dis[x]+lin[x][i].y;
            dfs(v);
            unio(x,v);
        }
    }
    for(int i=0;i<q[x].size();i++)
    {

        int v=q[x][i].x;
        if(vis[v]) ans[q[x][i].y]=dis[x]+dis[v]-2*dis[find(v)];

    }
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        init();
        for(int i=1;i"%d%d%d",&aa,&bb,&cc);
            lin[aa].push_back(node(bb,cc));
            lin[bb].push_back(node(aa,cc));
        }   

        for(int i=1;i<=m;i++)
        {

            scanf("%d%d",&aa,&bb);
            q[aa].push_back(node(bb,i));
            q[bb].push_back(node(aa,i));

        }

        dfs(1);
        for(int i=1;i<=m;i++)
        printf("%d\n",ans[i]);
    }
}

你可能感兴趣的:(图论)