思路:最大值最小首先想到二分,二分他花費最大公路的路費,這條路必定在一級公路上,然後通過克魯斯卡爾判斷是否能構成最小生成樹。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
typedef pair<int,int> PII;
const int mod=1e4+7;
const int N=2e6+10;
const int inf=0x7f7f7f7f;
ll gcd(ll a,ll b)
{
return b==0?a:gcd(b,a%b);
}
ll lcm(ll a,ll b)
{
return a*(b/gcd(a,b));
}
template <class T>
void read(T &x)
{
char c;
bool op = 0;
while(c = getchar(), c < '0' || c > '9')
if(c == '-')
op = 1;
x = c - '0';
while(c = getchar(), c >= '0' && c <= '9')
x = x * 10 + c - '0';
if(op)
x = -x;
}
template <class T>
void write(T x)
{
if(x < 0)
x = -x, putchar('-');
if(x >= 10)
write(x / 10);
putchar('0' + x % 10);
}
int n,m,k;
int p[N];
int vis[N];
struct node
{
int pos,w;
bool operator <(const node other)const
{
return w<other.w;
}
}b[2*N];
struct Edge
{
int u,v,w1,w2;
}edge[N];
int fnd(int x)
{
if(p[x]!=x)return p[x]=fnd(p[x]);
else return p[x];
}
int main()
{
SIS;
cin>>n>>k>>m;
for(int i=1;i<=m-1;i++)
{
cin>>edge[i].u>>edge[i].v>>edge[i].w1>>edge[i].w2;
b[i*2-1].w=edge[i].w1;
b[i*2].w=edge[i].w2;
b[i*2].pos=b[i*2-1].pos=i;
}
sort(b+1,b+1+(m-1)*2);
int l=1,r=m*2-2,mid;
int res=inf;
while(l<=r)
{
mid=(l+r)/2;
for(int i=0;i<=n;i++)
p[i]=i;
int cnt=0;
for(int i=1;i<=mid;i++)
{
int pos=b[i].pos;
if(edge[pos].w1>b[mid].w)continue;
int u=fnd(edge[pos].u),v=fnd(edge[pos].v);
if(u!=v)
{
p[u]v;
cnt++;
}
}
if(cnt<k){
l=mid+1;continue;
}
for(int i=1;i<=mid;i++)
{
int pos=b[i].pos;
int u=fnd(edge[pos].u),v=fnd(edge[pos].v);
if(u!=v)
{
p[u]=v;
cnt++;
}
}
if(cnt<n-1) l=mid+1;
else res=min(b[mid].w,res),r=mid-1;
}
cout<<res<<endl;
return 0;
}