結果

問題 No.1917 LCMST
ユーザー simansiman
提出日時 2022-04-30 17:33:43
言語 C++17(clang)
(17.0.6 + boost 1.87.0)
結果
AC  
実行時間 486 ms / 4,000 ms
コード長 2,165 bytes
コンパイル時間 1,589 ms
コンパイル使用メモリ 144,868 KB
実行使用メモリ 44,916 KB
最終ジャッジ日時 2024-06-29 22:41:36
合計ジャッジ時間 19,444 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 42
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <cassert>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <climits>
#include <map>
#include <queue>
#include <set>
#include <numeric>
#include <cstring>
#include <vector>

using namespace std;
typedef long long ll;

struct Edge {
  int from;
  int to;
  ll cost;

  Edge(int from = -1, int to = -1, ll cost = -1) {
    this->from = from;
    this->to = to;
    this->cost = cost;
  }

  bool operator>(const Edge &n) const {
    return cost > n.cost;
  }
};

class UnionFind {
public:
  vector<int> _parent;
  vector<int> _rank;
  vector<int> _size;

  UnionFind(int n) {
    for (int i = 0; i < n; ++i) {
      _parent.push_back(i);
      _rank.push_back(0);
      _size.push_back(1);
    }
  }

  int find(int x) {
    if (_parent[x] == x) {
      return x;
    } else {
      return _parent[x] = find(_parent[x]);
    }
  }

  void unite(int x, int y) {
    x = find(x);
    y = find(y);
    if (x == y) return;

    if (_rank[x] < _rank[y]) {
      _parent[x] = y;
      _size[y] += _size[x];
    } else {
      _parent[y] = x;
      _size[x] += _size[y];
      if (_rank[x] == _rank[y]) ++_rank[x];
    }
  }

  bool same(int x, int y) {
    return find(x) == find(y);
  }

  int size(int x) {
    return _size[find(x)];
  }
};

int main() {
  int N;
  cin >> N;
  vector<ll> A(N);
  ll ans = 0;
  ll M = 0;
  vector<ll> counter(100010, 0);

  for (int i = 0; i < N; ++i) {
    cin >> A[i];
    M = max(M, A[i]);
    counter[A[i]]++;
  }

  priority_queue <Edge, vector<Edge>, greater<Edge>> pque;
  vector<bool> checked(M + 1, false);

  for (ll d = 1; d <= M; ++d) {
    if (counter[d] > 0) {
      ans += d * (counter[d] - 1);
    }
    ll min_x = -1;

    for (ll x = d; x <= M; x += d) {
      if (counter[x] == 0) continue;

      if (checked[d]) {
        pque.push(Edge(min_x, x, min_x * x / d));
      } else {
        min_x = x;
        checked[d] = true;
      }
    }
  }

  UnionFind uf(100010);

  while (not pque.empty()) {
    Edge e = pque.top();
    pque.pop();

    if (uf.same(e.from, e.to)) continue;

    uf.unite(e.from, e.to);
    ans += e.cost;
  }

  cout << ans << endl;

  return 0;
}
0