题解:P14362 [CSP-S 2025] 道路修复 / road(民间数据)
题目意思
自己看题目。
思路
观察到可以把村庄当成超级节点。
题面说: 「原始图任意两座城市都能通过若干条道路相互到达。」
于是不难考虑到最小生成树,枚举
这时我们发现在循环里 建图+sort 是不行的,于是考虑先将所有边建好,在循环外 sort 。这时,我们发现如果用没有在升级方案 if(node[u] or node[v] is not in S) skip this edge
这样还是不行!我们在循环内遍历所有边做最小生成树,时间复杂度
最小生成树,顾名思义是一棵树,所以对于有
最终复杂度
AC 代码
#include <bits/stdc++.h>
using namespace std;
struct st{
int u, v, w;
}e[2000001];
int h[200001], a[50];
bool operator <(const st &a, const st &b){
return a.w < b.w;
}
int head(int x){
return (h[x] == x ? x : h[x] = head(h[x]));
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int n, m, k;
cin >> n >> m >> k;
for(int i = 1; i <= m; i++){
cin >> e[i].u >> e[i].v >> e[i].w;
}
int cnt = n;
for(int i = 1; i <= k; i++){
cnt++;
cin >> a[i];
for(int j = 1; j <= n; j++){
m++;
e[m].u = j;
e[m].v = cnt;
cin >> e[m].w;
}
}
sort(e + 1, e + m + 1);
long long ans = 9e18;
for(int i = 0; i < (1 << k); i++){
for(int i = 1; i <= cnt; i++){
h[i] = i;
}
int cnt = n - 1;
long long res = 0;
for(int j = 0; j < k; j++){
if(i & (1 << j)){
cnt++;
res += a[j + 1];
}
}
for(int j = 1; j <= m && cnt; j++){
int u = e[j].u, v = e[j].v, w = e[j].w;
if(v > n && !(i & (1 << (v - n - 1)))){
continue;
}
if(head(u) != head(v)){
cnt--;
h[h[v]] = h[u];
res += w;
}
}
ans = min(ans, res);
}
cout << ans;
return 0;
}