HDOJ 1598 Kruscal

时间:2023-03-09 18:38:08
HDOJ 1598 Kruscal

贪心思想的Kruscal:先对边排序,再从第一条边开始,一旦start point 和 end poiont 连上,就break

 #include <stdio.h>
#include <iostream>
#include <algorithm>
const int N = ;
const int inf = ;
using namespace std; struct Road{
int st,ed,pd; //起点,终点、速度
}road[N];
int cmp(const Road &p,const Road &q){
return p.pd<q.pd;
}
int root[N];
int n,m;
void init(){
for(int i = ; i <= n; i++){
root[i] = -;
}
}
int Find(int x){
int s = x;
while(root[s] >= ){ //一直查到parent[s]为负数(此时s为根结点)为止
s = root[s];
}
while(s != x){ //路径压缩,优化,便于后续的查找操作加速
int temp = root[x];
root[x] = s;
x=temp;
}
return s;
}
void Union(int R1,int R2){
int r1 = Find(R1);
int r2 = Find(R2);
if(r1 != r2){
root[r2] = r1;
}
}
int main(){
int _case;
while(scanf("%d%d",&n,&m)!=EOF){
for(int i = ; i <= m; i++){\
scanf("%d%d%d",&road[i].st,&road[i].ed,&road[i].pd);
}
sort(road+, road+ + m, cmp); //calculating form 1
scanf("%d",&_case);
while(_case--){
int st,ed;
int min = inf;
scanf("%d%d",&st,&ed);
for(int i = ; i <= m; i++){
init();
for(int j = i; j <= m; j++){
Union(road[j].st, road[j].ed);
if(Find(st) == Find(ed)){
int ans = road[j].pd - road[i].pd; //舒适度
min = ans < min ? ans : min;
break;
}
}
}
if(min == inf)
printf("-1\n");
else
printf("%d\n",min);
}
}
return ;
}