注意两个问题,第一个是在森林中,所以需要判断两个点是否是在一棵树中,第二个是求取路径时可以借助到根的路径长度来求取,类似于前缀和的一种优化
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <vector> #define MAX 20007 using namespace std; int n , m , c , u , v , w ; struct { int v , next , w; }e[MAX<<1]; struct { int v , next, index; }q[2000007]; int cc = 0; int head1[MAX]; int head2[MAX]; int fa[MAX]; int find ( int x ) { return fa[x] == x ? x : fa[x] = find ( fa[x] ); } void add1 ( int u , int v , int w ) { e[cc].v = v; e[cc].w = w; e[cc].next = head1[u]; head1[u] = cc++; } void add2 ( int u , int v , int i ) { q[cc].v = v; q[cc].next = head2[u]; q[cc].index = i; head2[u] = cc++; } int vis[MAX]; int root[MAX]; int dis[MAX]; int yes[1000007]; void init () { memset ( head1 , -1 , sizeof ( head1 ) ); memset ( head2 , -1 , sizeof ( head2 ) ); cc = 0; for ( int i = 1 ; i <= n+1 ; i++ ) fa[i] = i; memset ( vis , 0 , sizeof ( vis ) ); memset ( dis , 0 , sizeof ( dis ) ); memset ( root , 0 , sizeof ( root ) ); } void lca ( int u , int p , int r ) { vis[u] = 1; root[u] = r; for ( int i = head1[u] ; i != -1 ; i = e[i].next ) { int v = e[i].v; if ( v == p ) continue; dis[v] = dis[u] + e[i].w; lca ( v , u , r ); fa[v] = u; } for ( int i = head2[u] ; i != -1 ; i = q[i].next ) { int v = q[i].v; if ( root[v] != r ) continue; int l = find ( v ); yes[q[i].index] = dis[u] + dis[v] - 2*dis[l]; } } int main ( ) { while ( ~scanf ( "%d%d%d" , &n , &m , &c ) ) { init ( ); for ( int i = 0 ; i < m ; i++ ) { scanf ( "%d%d%d" , &u ,&v , &w ); add1 ( u , v , w ); add1 ( v , u , w ); } cc = 0; for ( int i = 0 ; i < c ; i++ ) { scanf ( "%d%d" , &u , &v ); add2 ( u , v , i ); add2 ( v , u , i ); } memset ( yes , -1 , sizeof ( yes ) ); for ( int i = 1 ; i <= n ; i++ ) if ( !vis[i] ) lca ( i , -1 , i ); for ( int i = 0 ; i < c ; i ++ ) if ( yes[i] == -1 ) printf ( "Not connected\n" ); else printf ( "%d\n" , yes[i] ); } return 0; }