HDU 2874

简单的tarjan

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

#define N 10010
#define M 20010
#define C 2001000
using namespace std;

struct edge{
	int v,c;
	int next;
}City[M];

struct query{
	int v,index;
	int next;
}Query[C];
int ctot,qtot;
int chead[N],qhead[N];
int fa[N];
int Value[N];
int ans[C/2];
int rts[N];

void addcedge(int u,int v,int c){
	City[ctot].v=v;
	City[ctot].c=c;
	City[ctot].next=chead[u];
	chead[u]=ctot++;
}

void addqedge(int u,int v,int c){
	Query[qtot].v=v;
	Query[qtot].index=c;
	Query[qtot].next=qhead[u];
	qhead[u]=qtot++;
}

int find(int u){
	int p=u;
	while(p!=fa[p])
	p=fa[p];
	while(u!=p){
		int r=fa[u];
		fa[u]=p;
		u=r;
	}
	return p;
}

void Union(int u,int v){
	int uf=find(u);
	int uv=find(v);
	fa[v]=uf;
}

void tarjan(int now,int pre,int val,int root){
	rts[now]=root;
	fa[now]=now;
	Value[now]=val;
	for(int e=chead[now];e!=-1;e=City[e].next){
		int v=City[e].v;
		if(v==pre) continue;
		tarjan(v,now,val+City[e].c,root);
		Union(now,v);
	}
	for(int e=qhead[now];e!=-1;e=Query[e].next){
		int v=Query[e].v;
		if(ans[Query[e].index]==-1&&rts[v]==root){
			int vf=find(v);
			ans[Query[e].index]=Value[v]+Value[now]-2*Value[vf];
		}
	}
}

int main(){
	int n,m,c,g; int u,v,q;
	while(scanf("%d%d%d",&n,&m,&c)!=EOF){
		memset(chead,-1,sizeof(chead));
		memset(qhead,-1,sizeof(qhead));
		memset(fa,-1,sizeof(fa));
		memset(Value,0,sizeof(Value));
		memset(ans,-1,sizeof(ans));
		memset(rts,0,sizeof(rts));
		ctot=qtot=0;
		for(int i=1;i<=m;i++){
			scanf("%d%d%d",&u,&v,&g);
			addcedge(u,v,g);
			addcedge(v,u,g);
		}
		for(int i=1;i<=c;i++){
			scanf("%d%d",&u,&v);
			addqedge(u,v,i);
			addqedge(v,u,i);
		}
		for(int i=1;i<=n;i++){
			if(fa[i]==-1)
			tarjan(i,-1,0,i);
		}
		for(int i=1;i<=c;i++){
			if(ans[i]!=-1)
			printf("%d\n",ans[i]);
			else puts("Not connected");
		}
	}
	return 0;
}

  

posted @ 2014-12-06 16:28  chenjunjie1994  阅读(140)  评论(0编辑  收藏  举报