第一、注意 head_tree[],head_query[]只需要开到节点的个数那么多就可以了,MLE了好几发才意识到的,尴尬
第二这个题目需要特判下这两个节点是不是在一棵树上
剩下的就是求LCA了
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int Tmaxn = 10000+2;
const int Qmaxn = 1000000+2;
struct tree{
int to,w,next;
}Tree[Tmaxn<<1];
struct query{
int to,next;
int id;
}Query[Qmaxn<<1];
int vist[Tmaxn],fat[Tmaxn],head_tree[Tmaxn],head_query[Tmaxn];//切记head开的和节点数一样就可以了
int cnt_tree,cnt_query;
int res[Qmaxn],dist[Tmaxn];
int N,M,Q;
void Init(){
cnt_tree = cnt_query = 0;
for(int i = 1; i <= N; i++){
head_tree[i] = head_query[i] = -1;
vist[i] = dist[i] = 0;
fat[i] = i;
}
}
int Find(int x){
if(x != fat[x])
x = Find(fat[x]);
return x;
}
void ADD_tree(int u,int v,int w){
Tree[cnt_tree].to = v;
Tree[cnt_tree].w = w;
Tree[cnt_tree].next = head_tree[u];
head_tree[u] = cnt_tree++;
}
void ADD_query(int u,int v,int id){
Query[cnt_query].to = v;
Query[cnt_query].id = id;
Query[cnt_query].next = head_query[u];
head_query[u] = cnt_query++;
}
void Tarjan(int u,int father,int flag){
for(int i = head_tree[u]; ~i; i = Tree[i].next){
int v = Tree[i].to;
if(!vist[v] && v!=father){
dist[v] = dist[u] + Tree[i].w;
Tarjan(v,u,flag);
fat[v] = u;
}
}
vist[u] = flag;
for(int i = head_query[u]; ~i; i = Query[i].next){
int v = Query[i].to;
if(vist[v]){
int temp = Find(v);
if(vist[v] == flag)
res[Query[i].id] = dist[u]+dist[v]-2*dist[temp];
else
res[Query[i].id] = -1;
}
}
}
int main(){
int u,v,w;
while(~scanf("%d %d %d",&N,&M,&Q)){
Init();
for(int i = 0; i < M; i++){
scanf("%d %d %d",&u,&v,&w);
ADD_tree(u,v,w);
ADD_tree(v,u,w);
}
for(int i = 0; i < Q; i++){
scanf("%d %d",&u,&v);
ADD_query(u,v,i);
ADD_query(v,u,i);
}
int cnt = 0;
for(int i = 1; i <= N; i++){
if(!vist[i]){
cnt++;
Tarjan(i,-1,cnt);
}
}
for(int i = 0; i < Q; i++){
if(res[i] == -1)
puts("Not connected");
else
printf("%d\n",res[i]);
}
}
return 0;
}