並查集加貪心
[cpp]
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
#define N 1010
#define INF 0x7fffffff
struct cam
{
int st,ed;
int speed;
}list[4*N];
int n,m;
int f[N];
void init()
{
int i;
for(i=1;i<=n;i++)
f[i]=i;
}
int find(int x)
{
int r=x;
while(f[r]!=r)
r=f[r];
f[x]=r;
return f[x];
}
void merge(int x,int y)
{
int xx,yy;
xx=find(x);
yy=find(y);
f[xx]=yy;
}
int cmp(const void *a,const void *b)
{
return (*(struct cam *)a).speed-(*(struct cam *)b).speed;
}
int main()
{
int i,j,t;
int x,y,xx,yy,ans;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=0;i<m;i++)
scanf("%d%d%d",&list[i].st,&list[i].ed,&list[i].speed);
qsort(list,m,sizeof(struct cam),cmp);
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&x,&y);
ans=INF;
for(i=0;i<m;i++)
{
init();
for(j=i;j<m;j++)
{
merge(list[j].st,list[j].ed);
if(find(x)==find(y))
{
if(ans>list[j].speed-list[i].speed)
ans=list[j].speed-list[i].speed;
break;
}
}
if(j==m)
break;
}
if(ans==INF)
printf("-1\n");
else
printf("%d\n",ans);
}
}
return 0;
}