Hdu 1598 find the most comfortable road (query set)

Source: Internet
Author: User

Idea: first sort all edges by z, and then enumerate them in sequence. During this period, we use and query the set for continuous merging,

It is used to determine whether the start and end can be connected. If yes, It is larger than the current ans;
If ans = inf, start and end cannot form a path.


**************************************** **************************************** **************************************** ********************

#include<algorithm>using namespace std;#define inf 99999999struct node{int x,y;int z;}a[5000];int pre[5000];int find(int k){if(k==pre[k])return k;return pre[k]=find(pre[k]);}int cmp(node a,node b){return a.z<b.z;}int main(){int n,m,t,start,end,f1,f2,ans,i,j;while(scanf("%d%d",&n,&m)!=EOF){for(i=0;i<m;i++)scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].z);sort(a,a+m,cmp);scanf("%d",&t);while(t--){scanf("%d%d",&start,&end);ans=inf;for(i=0;i<m;i++){for(j=1;j<=n;j++)pre[j]=j;for(j=i;j<m;j++){f1=find(a[j].x);f2=find(a[j].y);if(f1!=f2)pre[f1]=f2;f1=find(start);f2=find(end);if(f1==f2)break;}if(j>=m)break;if(a[j].z-a[i].z<ans)ans=a[j].z-a[i].z;}if(ans==inf)printf("-1\n");elseprintf("%d\n",ans);}}return 0;} 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.