220v
젝무의 개발새발
220v
전체 방문자
오늘
어제
  • 분류 전체보기 (255)
    • AI (35)
      • ML, DL 학습 (30)
      • 논문 리뷰 (4)
      • 실습 및 프로젝트 (1)
    • Algorithm (145)
      • LeetCode (13)
      • 프로그래머스 (35)
      • 백준 (96)
      • 알고리즘, 문법 정리 (1)
    • Mobile, Application (17)
      • Flutter (10)
      • iOS, MacOS (7)
    • BackEnd (7)
      • Flask (1)
      • Node.js (5)
      • Spring, JSP..etc (1)
    • Web - FrontEnd (18)
      • JavaScript, JQuery, HTML, C.. (12)
      • React (6)
    • DataBase (1)
      • MySQL (1)
      • Firebase Firestore (0)
      • Supabase (0)
    • Git (1)
    • 기타 툴 및 오류 해결 (3)
    • 강의 (5)
      • Database (3)
      • 암호학 (2)
      • 알고리즘 (0)
    • 후기와 회고 (2)
    • 블로그 꾸미기 (1)
    • 일상과 이것저것 (20)
      • 맛집 (12)
      • 세상사는일 (4)
      • 도서리뷰 (1)
      • 이런저런 생각들 (잡글) (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • Mathematics
  • Backtracking
  • union-find
  • 위상 정렬
  • 프로그래머스
  • 구현
  • Greedy
  • dfs
  • Prefix Sum
  • brute-Force
  • Priority Queue
  • top-down
  • Dynamic Programming
  • binary search
  • BFS
  • 다익스트라
  • dp
  • 티스토리챌린지
  • implementation
  • REACT
  • Lis
  • bitmasking
  • 백준
  • IMPLEMENT
  • simulation
  • disjoint set
  • Minimum Spanning Tree
  • two pointer
  • 오블완
  • topological sort

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
220v

젝무의 개발새발

Algorithm/백준

[백준] 1922. 네트워크 연결 - Python

2023. 10. 31. 03:00

[Gold IV]

 

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

 

1922번: 네트워크 연결

이 경우에 1-3, 2-3, 3-4, 4-5, 4-6을 연결하면 주어진 output이 나오게 된다.

www.acmicpc.net

 

풀이

기본적인 MST(Minimum Spanning Tree) 문제.

Kruskal 알고리즘을 통해 MST를 구현하였다.

응용된 것 없이 MST를 구현하기만 하면 되는 문제이므로 설명은 생략.

 

AC.

from collections import deque

# input
N = int(input())
M = int(input())
root = {i: i for i in range(1, N+1)}
edges = []
for _ in range(M):
    a, b, c = map(int, input().split())
    edges.append([c, a, b])

# Union-Find
def find(x):
    if root[x] == x:
        return x
    root[x] = find(root[x])
    return root[x]

def union(x, y):
    rx = find(x)
    ry = find(y)
    if rx < ry:
        root[ry] = rx
    else:
        root[rx] = ry
        
# MST
edges = sorted(edges)
result = 0
for cost, a, b in edges:
    if find(a) == find(b):
        continue
    
    union(a, b)
    result += cost
    
print(result)

 

    'Algorithm/백준' 카테고리의 다른 글
    • [백준] 20056. 마법사 상어와 파이어볼 - Python
    • [백준] 14719. 빗물 - Python
    • [백준] 1365. 꼬인 전깃줄 - Python
    • [백준] 2568. 전깃줄 - 2 - Python
    220v
    220v
    DGU CSE 20 / Apple Developer Academy @ POSTECH 2nd Jr.Learner.

    티스토리툴바