CF1095F Make It Connected

· · 个人记录

\color{black}CF1095F Make It Connected

第一道紫题,不过是卡过去的

题意

有 n 个点,每个点有个权值,如果想要把两个点连起来,就需要花费两个点的权值和,还给你了 m 条路径,路径的两边的两个点可以只花一个指定的数,问想让这个图变成连通图,最小要花费多少。

思路

很明显是最小生成树,但是如果用常规的 kruskal 板子——得把边全部建完才能求,是不可能的,不仅时间会炸,空间也会炸,所以用贪心的思路,把权值排序用做P1631 序列合并的方法,把两个权值中的第一个来划分组,如果知道当前答案,那么下一个答案要么是当前分组的下一个,要么是已经入堆的最小值,然后用并查集来求是否有环,没环就加上这条边。

代码

#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;
}

时间复杂度

说实话这应该是:O(n^2logn)

建边:最坏 O(n^2)

插入堆:O(logn)

用 map 反而比 unordered\_map 快一些(真的无语)。

空间复杂度

堆:O(n)

存储点的信息:O(n)

总共:O(n)