F. Dense spanning tree ###K //K

题目链接:https://codeforces.ml/edu/course/2/lesson/7/2/practice/contest/289391/problem/F

题意:求图中的一棵生成树 要求边权的最大值-最小值 最小

根据数据范围可以考虑  排序后 枚举起点 最小的肯定在其Kruskal顺序中产生

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int maxn=1e4+10;
 4 #define ll long long
 5 #define pb push_back
 6 
 7 struct ac
 8 {
 9   int u,v,w;
10   bool operator<(ac a)
11   {
12     return w<a.w;
13   }
14 };
15 ac a[maxn];
16 int f[maxn];
17 
18 int find1(int x)
19 {
20   if(x==f[x])
21     return x;
22   return f[x]=find1(f[x]);
23 }
24 void add(int x,int y)
25 {
26   int t1=find1(x),t2=find1(y);
27   f[t1]=t2;
28 }
29 
30 
31 
32 
33 int main()
34 {
35   ios::sync_with_stdio(0);
36   cin.tie(0);
37   int n,m;
38   cin>>n>>m;
39   for(int i=1;i<=m;i++)
40   {
41     int u,v,w;
42     cin>>u>>v>>w;
43     a[i].u=u,a[i].v=v,a[i].w=w;
44   }
45   sort(a+1,a+1+m);
46   int ans=2e9+10;
47   for(int i=1;i<=m;i++)
48   {
49       int tot=0;
50       int min1=1e9+5;
51       int max1=-1e9-5;
52       for(int j=1;j<=n;j++)
53         f[j]=j;
54       for(int j=i;j<=m;j++)
55       {
56           int u=a[j].u,v=a[j].v,w=a[j].w;
57           if(find1(u)!=find1(v))
58           {
59             max1=max(max1,w);
60             min1=min(min1,w);
61             add(u,v);
62             tot++;
63           }
64           if(tot==n-1)
65           {
66             ans=min(ans,max1-min1);
67             break;
68           }
69       }
70   }
71   if(ans==2e9+10)
72     cout<<"NO"<<'\n';
73   else
74     cout<<"YES"<<'\n'<<ans<<'\n';
75 
76 
77 
78 
79 
80 
81 
82 }
View Code

 

posted @ 2020-12-11 14:27  canwinfor  阅读(219)  评论(0)    收藏  举报