Notice
Recent Posts
Recent Comments
Link
«   2026/06   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Archives
Today
Total
관리 메뉴

dh-winternagi 님의 블로그

(6497) 전력난 본문

백준 (C++)/Solve

(6497) 전력난

dh-winternagi 2026. 4. 20. 19:19

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

단계별로 풀어보기

35단계(최소 신장 트리) 5번째

 

 

 

스패닝 트리를 만들 수 있는 만큼의 불은 켜둬야 한다. 이때 절약하는 돈은 입력받은 거리 총합-스패닝 트리 비용이므로, 이 값을 최대로 만들기 위해서는 스패닝 트리를 최소로, 즉 최소 신장 트리를 만들어야 한다.

 

 

 

#include <iostream>
#include <queue>
using namespace std;
typedef pair<int, int> p;

int solve(int m, int n){
  vector adj(m, vector<p> ());
  vector<bool> visited(m);
  priority_queue<p, vector<p>, greater<p>> pq;
  int s= 0;
  
  while(n--){
    int x, y, z;
    
    cin >> x >> y >> z;
    
    s+= z;
    adj[x].push_back({z,y});
    adj[y].push_back({z,x});
  }
  
  visited[0]= true;
  for(p edge:adj[0])  pq.push(edge);
  
  int cnt= 1, cost= 0;
  
  while(!pq.empty()){
    p now= pq.top();
    pq.pop();
    
    if(visited[now.second])  continue;
    
    visited[now.second]= true;
    cnt++;
    cost+= now.first;
    
    if(cnt==m)  break;
    
    for(p next:adj[now.second]){
      if(visited[next.second])  continue;
      
      pq.push({next.first, next.second});
    }
  }
  
  return s-cost;
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  
  while(true){
    int m, n;
    
    cin >> m >> n;
    
    if(!m)  break;
    
    cout << solve(m, n) << "\n";
  }
  
  return 0;
}

'백준 (C++) > Solve' 카테고리의 다른 글

(15681) 트리와 쿼리  (0) 2026.04.20
(17472) 다리 만들기 2  (0) 2026.04.20
(1774) 우주신과의 교감  (0) 2026.04.20
(4386) 별자리 만들기  (0) 2026.04.20
(1197) 최소 스패닝 트리  (0) 2026.04.20