#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
const int maxn = 10005;
const int maxm = maxn;
int head[ maxn ],cnt;
struct node{
int from,to,val,next;
}edge[ maxm<<2 ];
int deep[ maxn ],dis[ maxn ],fa[ maxn ];
int ace[ maxn ];//最近公共祖先
int n,m,q;
void init(){
memset( head,-1,sizeof( head ));
cnt=0;
memset( fa,0,sizeof( fa ));
}
void addedge( int a,int b,int c ){
edge[ cnt ].from=a;
edge[ cnt ].to=b;
edge[ cnt ].next=head[ a ];
edge[ cnt ].val=c;
head[ a ]=cnt++;
}
int find( int x,int y ){
if( x==y ) return x;
if( deep[ x ]>deep[ y ] )
return find( fa[ x ],y );
else
return find( x,fa[ y ] );
}
void dfs( int now,int now_father,int now_ace,int now_deep,int now_dis ){
fa[ now ]=now_father;
deep[ now ]=now_deep;
dis[ now ]=now_dis;
ace[ now ]=now_ace;
for( int i=head[ now ];i!=-1;i=edge[ i ].next ){
int v=edge[ i ].to;
if( fa[ v ]==0 )
dfs( v,now,now_ace,now_deep+1,now_dis+edge[ i ].val );
}
}
int main(){
while( scanf("%d%d%d",&n,&m,&q)==3 ){
int a,b,c;
init();
while( m-- ){
scanf("%d%d%d",&a,&b,&c);
addedge( a,b,c );
addedge( b,a,c );
}
for( int i=1;i<=n;i++ ){
if( fa[ i ]==0 ){
dfs( i,-1,i,0,1 );
}
}
while( q-- ){
scanf("%d%d",&a,&b);
if( ace[ a ]==ace[ b ] ){
int father=find( a,b );
printf("%d\n",dis[ a ]+dis[ b ]-2*dis[ father ]);
}
else printf("Not connected\n");
}
}
return 0;
}
tjut 2874
最新推荐文章于 2016-11-04 22:02:44 发布