HDU1598-find the most comfortable road
http://acm.hdu.edu.cn/showproblem.php?pid=1598
#include<iostream> #include<cstdio> #include<cstdlib> #define INF 10000000 #define N 1000 using namespace std; int n,m; struct Edge { int s,t,w; }edge[N+10]; int fa[205]; int cmp(const void *f1,const void *f2) { return (*(struct Edge *)f1).w-(*(struct Edge *)f2).w; } int find(int x) { return fa[x]==x?x:fa[x]=find(fa[x]); } int main(void) { int i,j,Q,s,e,min,x,y; while(scanf("%d%d",&n,&m)!=EOF) { for(i=0;i<m;i++) scanf("%d%d%d",&edge[i].s,&edge[i].t,&edge[i].w); qsort(edge,m,sizeof(edge[0]),cmp); scanf("%d",&Q); while(Q--) { scanf("%d%d",&s,&e); min=INF; for(i=0;i<m;i++) { for(j=0;j<=n;j++) fa[j]=j; for(j=i;j<m;j++) { x=find(edge[j].s); y=find(edge[j].t); if(x!=y) fa[x]=y; if(find(s)==find(e)) { min=min>edge[j].w-edge[i].w?edge[j].w-edge[i].w:min; break; } } } if(min!=INF) printf("%d\n",min); else printf("-1\n"); } } return 0; }