find the most comfortable road
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 2759 Accepted Submission(s): 1176
#include<iostream>
#include<cstdio>
#include<algorithm>
#define INT_MAX 10000000
using namespace std;
int father[1000000];
int n,m,q; struct edge
{
int s,e,w;
}ed[1000005];
int find(int x)
{
return x==father[x]?x:father[x]=find(father[x]);
}
void union_set(int x,int y)
{
father[find(x)]=find(y);
}
void makeset()
{
int i;
for(i=1;i<=n;i++)
father[i]=i;
}
int cmp(edge a,edge b)
{
return a.w<b.w;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
int i,j,x,y,min;
for(i=0;i<m;i++)
{
scanf("%d%d%d",&ed[i].s,&ed[i].e,&ed[i].w);
}
scanf("%d",&q);
sort(ed,ed+m,cmp);
while(q--)
{
scanf("%d%d",&x,&y);
min=INT_MAX;
for(i=0;i<m;i++)
{
makeset();
for(j=i;j<m;j++)
{
union_set(ed[j].s,ed[j].e);
if(find(x)==find(y))
break;
}
if(j==m)
break;
if(min>ed[j].w-ed[i].w)
min=ed[j].w-ed[i].w;
}
if(min==INT_MAX)
printf("-1 ");
else
printf("%d ",min);
}
}
return 0;
}