hdu1598_贪心+并查集=最短路

//贪心+并查集,对所有边排序,然后枚举每一条边,每条边的两个点合并为一个集合,当出现通路时就结束 #include<iostream> #include<cstdio> #include<algorithm> using namespace std; int p[105]; int n,m,q; struct edge { int s,e; int w; }ed[10005]; int find(int x) { while(p[x]!=x) x=p[x]; return x; } void union_set(int x,int y) { p[find(x)]=find(y); } void init() { for(int i=1;i<=n;i++) p[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; 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); int x,y; int min; while(q--) { scanf("%d%d",&x,&y); min=INT_MAX; for(i=0;i<m;i++) { init(); 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/n"); else printf("%d/n",min); } } return 0; }  

你可能感兴趣的:(hdu1598_贪心+并查集=最短路)