题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1196
题目大意:某城市要修建n-1条路使n个城市连通,要求n-1条路中必须有k条为高级公路,求花费最多的一条公路最少为多少
使最大值最小是二分的典型问题,直接二分最大值,然后跑最小生成树判断是否能够修建即可
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
struct Link
{
int s,t,c1,c2;
}l[50000];
int n,m,k;
int fa[20000];
int father(int x)
{
if(fa[x] != x)
fa[x] = father(fa[x]);
return fa[x];
}
bool same(int x,int y)
{
return father(x) == father(y);
}
void add(int x,int y)
{
fa[father(x)] = father(y);
return ;
}
bool cmp1(Link x,Link y)
{
return x.c1 < y.c1;
}
bool cmp2(Link x,Link y)
{
return x.c2 < y.c2;
}
bool judge(int x)
{
sort(l+1,l+m+1,cmp1);
int p = 0;
for(int i = 1;p < k;i ++)
{
if(l[i].c1 > x || i > m)
return 0;
if(!same(l[i].s,l[i].t))
{
add(l[i].s,l[i].t);
p ++;
}
}
sort(l+1,l+m+1,cmp2);
p = 0;
for(int i = 1;p < n-k-1;i ++)
{
if(l[i].c2 > x || i > m)
return 0;
if(!same(l[i].s,l[i].t))
{
add(l[i].s,l[i].t);
p ++;
}
}
return 1;
}
int main()
{
int s,t,c1,c2;
scanf("%d%d%d",&n,&k,&m);
for(int i = 1;i <= m;i ++)
{
scanf("%d%d%d%d",&s,&t,&c1,&c2);
l[i].s = s;
l[i].t = t;
l[i].c1 = c1;
l[i].c2 = c2;
}
int l = 0,r = 50000;
while(l != r)
{
for(int i = 1;i <= n;i ++)
fa[i] = i;
int mid = (l + r) / 2;
if(judge(mid))
r = mid;
else
l = mid + 1;
}
cout << l << endl;
}