백준 알고리즘 21924번 : 도시 건설

Zoo Da·2021년 8월 31일
0

백준 알고리즘

목록 보기
195/337
post-thumbnail

링크

https://www.acmicpc.net/problem/21924

문제

채완이는 신도시에 건물 사이를 잇는 양방향 도로를 만들려는 공사 계획을 세웠다.

공사 계획을 검토하면서 비용이 생각보다 많이 드는 것을 확인했다.

채완이는 공사하는 데 드는 비용을 아끼려고 한다.

모든 건물이 도로를 통해 연결되도록 최소한의 도로를 만들려고 한다.

위 그림에서 건물과 직선으로 표시된 도로, 해당 도로를 만들 때 드는 비용을 표시해놓은 지도이다.

그림에 있는 도로를 다 설치할 때 드는 비용은 62이다. 모든 건물을 연결하는 도로만 만드는 비용은 27로 절약하는 비용은 35이다.

채완이는 도로가 너무 많아 절약되는 금액을 계산하는 데 어려움을 겪고 있다.

채완이를 대신해 얼마나 절약이 되는지 계산해주자.

입력

출력

예산을 얼마나 절약 할 수 있는지 출력한다. 만약 모든 건물이 연결되어 있지 않는다면 -1을 출력한다.

예제 입력 및 출력

풀이 코드(C++)

#include <bits/stdc++.h>
#define X first
#define Y second
#define pb push_back
#define sz(a) int((a).size())
#define fastio ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
using namespace std;
using ll = long long;
using ull = unsigned long long;
using dbl = double;
using ldb = long double;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
using vi = vector<int>;
using wector = vector<vector<int>>;
using tii = tuple<int,int,int>;

const ll INF = 0x3f3f3f3f;

struct UnionFind {
	vector<int> parent, rank, cnt;
	UnionFind(int n) : parent(n), rank(n, 1), cnt(n, 1) {
		iota(parent.begin(), parent.end(), 0);
	}
	int Find(int x) {
		return x == parent[x] ? x : parent[x] = Find(parent[x]);
	}
	bool Union(int a, int b) {
		a = Find(a), b = Find(b);
		if (a == b) return 0;
		if (rank[a] < rank[b]) swap(a, b);
		parent[b] = a;
		rank[a] += rank[a] == rank[b];
		cnt[a] += cnt[b];
		return 1;
	}
};

int main() {
	fastio;
  int n,m; cin >> n >> m;
  vector<tuple<ll,ll,ll>> e;
  ll allCost = 0;
  for(int i = 0; i < m; i++){
    ll a,b,c; cin >> a >> b >> c;
    e.pb({c,a,b});
    allCost += c;
  }
  sort(e.begin(), e.end());
  UnionFind UF(n + 1);
  int cnt = 0;
  for(auto [c,a,b] : e){
    a = UF.Find(a);
    b = UF.Find(b);
    if(a == b) continue;
    UF.Union(a, b);
    allCost -= c;
    cnt++;
    if(cnt == n - 1) break;
  }
  cout << (cnt != n - 1 ? -1 : allCost) << "\n";
  return 0;
}

기본 MST문제였습니다.
간선의 가중치가 int형을 넘어가기 때문에 long long형으로 설정하는 것에만 주의하면 됩니다.

무지성 제출은 전설이다...

profile
메모장 겸 블로그

0개의 댓글