BOJ 1922 : 네트워크 연결 (Gold 4)
- 크루스칼 알고리즘으로 MST를 만들어 해결했다.
#include <bits/stdc++.h>
using namespace std;
using ti=array<int,3>;
using vi=vector<int>;
struct DisjointSet {
vi parent;
DisjointSet(int n) {
parent.resize(n);
for (int i=0;i<n;i++){
parent[i]=i;
}
}
int find(int u) {
if (parent[u]==u) return u;
return parent[u]=find(parent[u]);
}
void merge(int u, int v) {
u=find(u), v=find(v);
parent[u]=v;
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, m; cin >> n >> m;
vector<ti> edges;
for (int i=0;i<m;i++) {
int a,b,c;
cin >> a >> b >> c;
if (a==b) continue;
edges.push_back({c,a,b});
}
sort(edges.begin(), edges.end());
int res=0;
DisjointSet ds(n+1);
for (auto [c,a,b] : edges) {
if (ds.find(a)!=ds.find(b)) {
res += c;
ds.merge(a,b);
}
}
cout << res;
}
BOJ 4386 : 별자리 만들기 (Gold 3)
- Kruskal로 한 번, Prim으로 한 번 풀었다.
#include <bits/stdc++.h>
using namespace std;
using vi=vector<int>;
using pi=pair<int,int>;
struct DisjointSet {
vi parent, rank;
int max_rank=0;
DisjointSet(int n) {
parent.resize(n);
rank.resize(n, 1);
for (int i=0;i<n;i++)
parent[i]=i;
}
int find(int u) {
if (parent[u]==u) return u;
return parent[u]=find(parent[u]);
}
void merge(int u, int v) {
u=find(u), v=find(v);
if (rank[v] > rank[u]) swap(u, v);
parent[v] = u;
rank[u] += rank[v];
max_rank = max(max_rank, rank[u]);
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n; cin >> n;
priority_queue<pair<double, pi>, vector<pair<double, pi>>, greater<>> lines;
vector<pair<double, double>> points(n);
for (int i=0;i<n;i++) {
double x, y; cin >> x >> y;
points[i] = {x, y};
}
for (int i=0;i<n;i++) {
for (int j=0;j<n;j++) {
if (i==j) continue;
lines.push({(points[i].first-points[j].first)*(points[i].first-points[j].first)
+ (points[i].second-points[j].second)*(points[i].second-points[j].second), {i, j}});
}
}
DisjointSet ds(n);
double res=0;
while (ds.max_rank < n && !lines.empty()) {
auto [len, points] = lines.top(); lines.pop();
if (ds.find(points.first)!=ds.find(points.second)) {
res += sqrt(len);
ds.merge(points.first, points.second);
}
}
cout << res;
}
#include <bits/stdc++.h>
using namespace std;
using vi=vector<int>;
using pi=pair<int,int>;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n; cin >> n;
vector<pair<double, double>> points(n);
for (int i=0;i<n;i++) {
double x, y; cin >> x >> y;
points[i] = {x, y};
}
priority_queue<pair<double, int>, vector<pair<double, int>>, greater<>> pq;
bitset<100> visited;
pq.emplace(0, 0);
double res=0;
while (!pq.empty()) {
auto [w, u] = pq.top(); pq.pop();
if (visited[u]) continue;
visited[u] = true;
res += w;
for (int v=0;v<n;v++) {
if (u == v) continue;
if (visited[v]) continue;
pq.emplace(sqrt((points[u].first-points[v].first)*(points[u].first-points[v].first)
+(points[u].second-points[v].second)*(points[u].second-points[v].second)), v);
}
}
cout << res;
}