本文搬运自本人初中博客园博客,若图片加载不出来,可到原文查看:https://www.cnblogs.com/zhangtingxi/p/15568359.html

题目链接

题外话:

一道纯最小生成树的题,能出道蓝我也真服了…


本文默认使用kruskal算法,主要是因为另一种我不会

首先我们先满足 kk 条一级道路,对所有道路按一级道路造价排序,然后用最小生成树的做法选出 kk 条边。

对于剩下的道路按二级造价排序,然后同理继续选即可。

时间复杂度 O(nlogn)O(n\log n)

需要注意的是题目输出格式有误,后面是输出具体方案。第一个数代表选的边的编号,第二个数表示一级还是二级道路。

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Problem: P2323 [HNOI2006]公路修建问题
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P2323
// Memory Limit: 125 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read(){int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;
ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+
(x<<3)+(ch^48);ch=getchar();}return x*f;}
//#define M
//#define mo
#define N 20010
struct node
{
int x, y, yi, er, id;
}d[N];
struct Node
{
int x, y;
}cnt[N];
int n, m, i, j, k;
int fa[N], ans, p, x, y;

int dfs(int x)
{
if(fa[x]==x) return x;
return fa[x]=dfs(fa[x]);
}

bool cmp(node x, node y)
{
return x.yi<y.yi;
}

bool Cmp(node x, node y)
{
return x.er<y.er;
}

signed main()
{
// freopen("tiaoshi.in", "r", stdin);
// freopen("tiaoshi.out", "w", stdout);
n=read(); p=read(); m=read();
for(i=1; i<=n; ++i) fa[i]=i;
for(i=1; i<m; ++i)
{
d[i].x=read(); d[i].y=read();
d[i].yi=read(); d[i].er=read();
d[i].id=i;
}
sort(d+1, d+m, cmp);
for(i=1, j=0; j<p; ++i)
{
x=dfs(d[i].x);
y=dfs(d[i].y);
if(x==y) continue;
fa[x]=y; ++j;
cnt[j].x=d[i].id; cnt[j].y=1;
}
ans=d[i-1].yi;
sort(d+i+1, d+m, Cmp);
for(; j<n-1; ++i)
{
x=dfs(d[i].x);
y=dfs(d[i].y);
if(x==y) continue;
fa[x]=y; ++j;
// printf("%lld 2\n", d[i].id);
cnt[j].x=d[i].id; cnt[j].y=2;
}
ans=max(ans, d[i-1].er);
printf("%lld\n", ans);
for(i=1; i<n; ++i) printf("%lld %lld\n", cnt[i].x, cnt[i].y);
return 0;
}