結果

問題 No.1917 LCMST
ユーザー SSRS
提出日時 2022-04-29 22:07:29
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 442 ms / 4,000 ms
コード長 1,438 bytes
コンパイル時間 1,734 ms
コンパイル使用メモリ 181,084 KB
実行使用メモリ 42,616 KB
最終ジャッジ日時 2024-06-29 03:36:32
合計ジャッジ時間 16,895 ms
ジャッジサーバーID
(参考情報)
judge5 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 42
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
const int MAX = 100001;
struct unionfind{
	vector<int> p;
	unionfind(int N){
		p = vector<int>(N, -1);
	}
	int root(int x){
		if (p[x] < 0){
			return x;
		} else {
			p[x] = root(p[x]);
			return p[x];
		}
	}
	bool same(int x, int y){
		return root(x) == root(y);
	}
	void unite(int x, int y){
		x = root(x);
		y = root(y);
		if (x != y){
			if (p[x] < p[y]){
				swap(x, y);
			}
			p[y] += p[x];
			p[x] = y;
		}
	}
};
int main(){
  int N;
  cin >> N;
  vector<int> A(N);
  for (int i = 0; i < N; i++){
    cin >> A[i];
  }
  vector<int> cnt(MAX, 0);
  for (int i = 0; i < N; i++){
    cnt[A[i]]++;
  }
  vector<tuple<long long, int, int>> E;
  for (int i = 1; i < MAX; i++){
    vector<int> p;
    for (int j = i; j < MAX; j += i){
      if (cnt[j] > 0){
        p.push_back(j);
      }
    }
    if (p.size() >= 2){
      int cnt2 = p.size();
      for (int j = 1; j < cnt2; j++){
        long long c = (long long) p[0] * p[j] / i;
        E.push_back(make_tuple(c, p[0], p[j]));
      }
    }
  }
  sort(E.begin(), E.end());
  int M = E.size();
  unionfind UF(MAX);
  long long ans = 0;
  for (int i = 0; i < M; i++){
    int u = get<1>(E[i]);
    int v = get<2>(E[i]);
    if (!UF.same(u, v)){
      UF.unite(u, v);
      ans += get<0>(E[i]);
    }
  }
  for (int i = 0; i < MAX; i++){
    if (cnt[i] >= 2){
      ans += (long long) i * (cnt[i] - 1);
    }
  }
  cout << ans << endl;
}
0