Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

boj 6497 전력난 #959

Merged
merged 1 commit into from
Oct 20, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions 최소 스패닝 트리/Kruskal/6497.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
#include <iostream>
#include <vector>
#include <algorithm>
#define MAX 200001
using namespace std;

typedef struct Node {
int u, v, w;
}Node;

Node list[MAX];
int parent[MAX];
int N, M, sum;

bool cmp(Node a, Node b) {
return a.w < b.w;
}

void init() {
for (int i = 0; i < N; i++) {
parent[i] = i;
}
}

int find(int v) {
if (parent[v] == v) return v;
return parent[v] = find(parent[v]);
}

bool unionNode(int u, int v) {
u = find(u);
v = find(v);

if (parent[u] != parent[v]) {
parent[v] = parent[u];
return true;
}

return false;
}

void func() {
init();

sort(list, list + M, cmp);

int ret = 0;
int cnt = 0;
for (int i = 0; i < M; i++) {
int u = list[i].u;
int v = list[i].v;

if (unionNode(u, v)) {
ret += list[i].w;
cnt++;
}

if (cnt == N - 1) break;
}

cout << sum - ret << '\n';
}

void input() {
cin >> N >> M;
if (!N && !M) exit(0);

sum = 0;
for (int i = 0; i < M; i++) {
cin >> list[i].u >> list[i].v >> list[i].w;
sum += list[i].w;
}
}

int main() {
cin.tie(NULL); cout.tie(NULL);
ios::sync_with_stdio(false);

while (1) {
input();
func();
}

return 0;
}