CF1095F Make It Connected
\color{black}CF1095F Make It Connected
第一道紫题,不过是卡过去的
题意
有
思路
很明显是最小生成树,但是如果用常规的
代码
#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
using namespace std;
using ll = long long;
const int MaxN = 2e5 + 10;
struct S {
ll x, y, z;
bool operator<(const S &j) const {
if (z != j.z) {
return z > j.z;
}
return x != j.x ? x < j.x : y < j.y;
}
};
struct E {
ll x, id;
bool operator<(const E &j) const {
return x < j.x;
}
} a[MaxN];
ll n, m, ans;
int fa[MaxN], l[MaxN];
priority_queue<S> q;
map<int, ll> b[MaxN];
int FindFather(int x) {
return fa[x] < 0 ? x : fa[x] = FindFather(fa[x]);
}
void insert(int x, int y) {
x = FindFather(x), y = FindFather(y);
if (x == y) {
return;
}
if (fa[x] < fa[y]) {
swap(x, y);
}
fa[y] += fa[x], fa[x] = y;
}
void inpq(int x, int y) {
ll tmp = b[a[x].id][a[y].id];
if (tmp != 0) {
q.push({x, y, min(a[x].x + a[y].x, tmp)});
} else {
q.push({x, y, a[x].x + a[y].x});
}
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
fa[i] = -1;
cin >> a[i].x;
a[i].id = i;
}
sort(a + 1, a + n + 1);
for (int i = 1; i <= n; i++) {
l[a[i].id] = i;
}
for (int i = 1; i <= m; i++) {
ll x, y, w;
cin >> x >> y >> w;
b[x][y] = b[y][x] = w;
inpq(l[x], l[y]);
}
for (int i = 2; i <= n; i++) {
inpq(i, 1);
}
for (int i = 1; i <= n - 1;) {
S u = q.top();
q.pop();
if (FindFather(u.x) != FindFather(u.y)) {
ans += u.z;
// cout << u.x << " " << u.y << " " << u.z << endl;
insert(u.x, u.y);
i++;
}
if (u.y + 1 <= n && (u.x == u.y + 1 && u.y + 2 <= n)) {
inpq(u.x, u.y + 1 + (u.y + 1 == u.x));
}
}
cout << ans << endl;
return 0;
}
时间复杂度
说实话这应该是:
建边:最坏
插入堆:
用
空间复杂度
堆:
存储点的信息:
总共: