跳到正文

题解

题解:P7390 「EZEC-6」造树

ChickyHas_AFO约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年7月24日
更新
2026年11月9日
篇幅
约 3 分钟
获赞
3
题目
P7390

版本

  1. v1当前

这题放模拟赛 T1 实在是妙啊!

将点按照 bib_i 从大到小排序,每次和能连的 bib_i 最大的点连边。

原因是考虑 a<b<c<da<b<c<d 显然有 ab+cd>ac+bdab+cd>ac+bd

如果两个点连边之后使得某个连通块不会再有出边,或者连完之后出现了环,那么就是不能连的,否则就可以连。

具体的,用两个队列来维护。最终肯定是一棵树,也就是一个连通块,那么我们一个队列维护最终的连通块中,能连出去的 bib_i 的值。另一个维护剩着的度数为 1 的连通块中还能连出去的 bib_i。每次先和最终的连通块连边,然后把当前点加入最后连通块中,然后与度数为 1 的连通块再去一一配对,如果第一个队列为大小为 1,就把它也放到度数为 1 的那一类去。

给个 std 实现:

C++
#include <bits/stdc++.h>

using namespace std;
using ll = long long;

const int N = 2e7 + 5;

int op, n, p[N], q[N];
unsigned seed;
ll ans;

struct A {
  int d, w;
} a[N];

unsigned rnd() {
  seed ^= seed << 13, seed ^= seed >> 17, seed ^= seed << 5;
  return seed;
}

int rand(int l, int r) {
  return rnd() % (r - l + 1) + l;
}

int main() {
  ios::sync_with_stdio(0);
  cin.tie(0), cout.tie(0);
  cin >> op >> n;
  if (!op) {
    for (int i = 1; i <= n; ++i) {
      cin >> a[i].d;
    }
    for (int i = 1; i <= n; ++i) {
      cin >> a[i].w;
    }
  } else {
    cin >> seed;
    for (int i = 1; i <= n; ++i) {
      a[i].d = 1, a[i].w = rand(1, 500000);
    }
    for (int i = 1; i <= n - 2; ++i) {
      ++a[rand(1, n)].d;
    }
  }
  sort(a + 1, a + 1 + n, [](A i, A j) { return i.w > j.w; });
  int ph = 1, pt = 0, qh = 1, qt = 0;
  for (int i = 1; i <= n; ++i) {
    if (ph > pt) {
      while (a[i].d--) {
        p[++pt] = a[i].w;
      }
    } else {
      ans += 1ll * p[ph++] * a[i].w;
      while (--a[i].d) {
        p[++pt] = a[i].w;
      }
    }
    while (ph < pt && qh <= qt) {
      ans += 1ll * p[ph++] * q[qh++];
    }
    if (ph == pt) {
      q[++qt] = p[ph++];
    }
  }
  ans += 1ll * q[qh] * q[qt];
  cout << ans;
  return 0;
}
原文
存档评论2 条抓取于