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)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

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

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
220v

젝무의 개발새발

Algorithm/백준

[백준] 1647. 도시 분할 계획 - python

2023. 4. 23. 01:15

[Gold IV]

 

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

 

1647번: 도시 분할 계획

첫째 줄에 집의 개수 N, 길의 개수 M이 주어진다. N은 2이상 100,000이하인 정수이고, M은 1이상 1,000,000이하인 정수이다. 그 다음 줄부터 M줄에 걸쳐 길의 정보가 A B C 세 개의 정수로 주어지는데 A번

www.acmicpc.net

 

풀이

문제를 딱 보고서 생각한 것

-> Minimum Spanning Tree구나.

MST를 구현하고 나서, 남은 edge들 중 가장 value가 높은 것을 제거하면 될 것 같다.

 

line 13의 = 를 ==로 오타내서 찾는데 시간 좀 씀...ㅎ

아무튼 clear.

from collections import deque
N, M = map(int, input().split())
edges = [list(map(int, input().split())) for _ in range(M)]
edges = sorted(edges, key=lambda x: x[2])

dic = {i: i for i in range(1, N+1)}
result = []  # save costs for edges(result)


def find(x):  # Find(Union-Find), with optimization
    if dic[x] == x:
        return x
    dic[x] = find(dic[x])
    return dic[x]


def union(x, y):  # Union(Union-Find), connect to smaller one.
    rx = find(x)
    ry = find(y)
    if rx < ry:
        dic[ry] = rx
    else:
        dic[rx] = ry


for edge in edges:
    if len(result) == N-1:
        break

    a, b, c = edge
    # cycle 생성이 되지 않는다면,
    if find(a) != find(b):
        union(a, b)
        result.append(c)

print(sum(result) - max(result))
    'Algorithm/백준' 카테고리의 다른 글
    • [백준] 9095. 1, 2, 3 더하기 - 파이썬
    • [백준] 1987. 알파벳 - python
    • [백준] 12100. 2048 (Easy) - 파이썬
    • [백준] 11049. 행렬 곱셈 순서 - 파이썬
    220v
    220v
    DGU CSE 20 / Apple Developer Academy @ POSTECH 2nd Jr.Learner.

    티스토리툴바