백준일지

[백준] 6497번 전력난

민지기il 2025. 4. 7. 22:56

[ 최소 스패닝 트리 ]

: 주어진 간선에 대한 정보들을 통해서, 최소의 비용으로 모든 정점을 연결한다.

1. 크루스칼 알고리즘

모든 가중치를 오름차순으로 정렬 -> 가중치가 가장 작은 간선 선택 -> 두 정점이 연결 안되어 있다면(사이클도 존재 x) 연결 -> 이 과정을 반복

1) 서로 같은 부모를 갖는지 판단해주는 함수  

2) 1번 과정을 위해서, 부모를 찾는 find 함수  

3) 서로 다른 부모일 경우, 두 개의 노드를 연결해야 하므로, 합치는 union 함수

출처: https://yabmoons.tistory.com/186

 

2. 프림 알고리즘

임의의 한 점을 선택 -> 이 점과 연결된 정점들 중 짧은 간선 선택 -> 짧은 간선으로 선택된 정점 & 처음 정점들 중 가장 짧은 거리 선택 -> 이 과정을 반복하며 거리를 업데이트 -> N-1번 반복함

출처: https://yabmoons.tistory.com/362

#include <bits/stdc++.h>
#define fastio cin.tie(0)->sync_with_stdio(0)
using namespace std;

int M, N, total, result, answer;
int parent[200010];
bool flag;
vector <pair<int, pair<int,int>>> edge;

void initialize(){
    edge.clear();
    total=result=0;
    for(int i=0; i<200010; i++) parent[i] = i;
}
void input(){
    cin>>M>>N;
    if(M==0 && N==0){
        flag = true;
        return;
    }
    for(int i=0; i<N; i++){
        int a,b,c; cin>>a>>b>>c;
        edge.push_back(make_pair(c,make_pair(a, b)));
        total += c;
    }
}

int find_parent(int a){
    if(a==parent[a]) return a;
    else return parent[a] = find_parent(parent[a]);
}
bool sameparent(int a, int b){
    a = find_parent(a);
    b = find_parent(b);
    if (a==b) return true;
    return false;
}
void Union(int a, int b){
    a = find_parent(a);
    b = find_parent(b);
    parent[b]=a;
}
void solution(){
    sort(edge.begin(), edge.end());
    for (int i=0; i<edge.size(); i++)
    {
        int cost = edge[i].first;
        int node1 = edge[i].second.first;
        int node2 = edge[i].second.second;
        
        if(sameparent(node1, node2) == false){
            Union(node1, node2);
            result += cost;
        }
    }
    answer = total-result;
}

void solve(){
    while(1){
        initialize();
        input();
        if(flag == true) return;
        solution();
        cout<<answer<<'\n';
    }
}

int main(void){
    fastio;
    solve();
    return 0;
}

<참고>

https://yabmoons.tistory.com/402