B.海岛争霸
Time Limit: 2 Sec Memory Limit: 128 MB Submit: 130 Solved: 48 [Submit][Status][Web Board]Description
Input
Output
Sample Input
10 8
1 2 5
1 3 2
2 3 11
2 4 6
2 4 4
6 7 10
6 10 5
10 7 2
5
2 3
1 4
3 7
6 7
8 3
Sample Output
5
5
-1
5
-1
HINT
Source
题解:并差集;让找最小的最大危险系数;
暴力,从0到m假设每个为起点,加边,当加到两个点联通时,找最小值;
代码:
#include<iostream> #include<cstring> #include<cstdio> #include<cmath> #include<algorithm> #include<vector> using namespace std; #define mem(x,y) memset(x,y,sizeof(x)) #define SI(x) scanf("%d",&x) #define SL(x) scanf("%lld",&x) #define PI(x) printf("%d",x) #define PL(x) printf("%lld",x) #define P_ printf(" ") const int INF=0x3f3f3f3f; const double PI=acos(-1.0); typedef long long LL; int N; const int MAXN=110; int pre[MAXN]; int find(int x){ return pre[x]=pre[x]==x?x:find(pre[x]); //return x==pre[x]?x:pre[x]=find(pre[x]); } void init(){ for(int i=1;i<N;i++)pre[i]=i; } void merge(int x,int y){ int f1=find(x),f2=find(y); if(f1!=f2)pre[f1]=f2; } struct Node{ int u,v,w; }dt[MAXN]; int cmp(Node a,Node b){ return a.w<b.w; } int main(){ int M,Q,a,b,c,temp,ans,flot; SI(N);SI(M); for(int i=0;i<M;i++) scanf("%d%d%d",&dt[i].u,&dt[i].v,&dt[i].w); sort(dt,dt+M,cmp); SI(Q); while(Q--){ scanf("%d%d",&a,&b); ans=INF; for(int i=0;i<M;i++){ init(); temp=0; flot=0; for(int j=i;j<M;j++){ merge(dt[j].u,dt[j].v); temp=max(temp,dt[j].w); if(find(a)==find(b)){ flot=1; break; } } if(flot)ans=min(ans,temp); } if(ans==INF)puts("-1"); else printf("%d\n",ans); } return 0; }