๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’๊ณต๋ถ€/์•Œ๊ณ ๋ฆฌ์ฆ˜

[๋ฐฑ์ค€] 1647๋ฒˆ : ๋„์‹œ ๋ถ„ํ•  ๊ณ„ํš

by rindev 2021. 9. 25.

 

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

์ „์ฒด ๊ทธ๋ž˜ํ”„๋ฅผ 2๊ฐœ๋กœ ๋‚˜๋ˆ„๋Š”๋ฐ ๊ทธ ๋‚˜๋ˆ ์ง„ ๊ทธ๋ž˜ํ”„ ์•ˆ์—์„œ๋Š” ์„œ๋กœ ๋‹ค ์—ฐ๊ฒฐ์ด ๋ผ ์žˆ์–ด์•ผ ํ•œ๋‹ค๋Š” ์–˜๊ธฐ..... (๊ทผ๋ฐ ๋Œ€์ฒด ์›์ˆญ์ด๐Ÿ™Š ์–˜๊ธฐ๋Š” ์™œ ๋‚˜์˜จ๊ฑฐ์ง€???)

 

๐Ÿ“–์ ‘๊ทผ ๋ฐฉ๋ฒ•

  1. ํฌ๋ฃจ์Šค์นผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ด์šฉํ•ด์„œ ์ตœ์†Œ์‹ ์žฅ ํŠธ๋ฆฌ๋ฅผ ํ•˜๋‚˜ ๋งŒ๋“ฌ
  2. ๊ทธ ์ค‘์—์„œ ๊ฐ€์žฅ ๋น„์‹ผ ๊ฐ„์„ ์„ ํ•˜๋‚˜ ์—†์•ค๋‹ค (๊ทธ๋ž˜์•ผ ์ตœ์†Œ ๋น„์šฉ์ด ๋˜๋‹ˆ๊นŒ!)
  3. ๊ทธ๋Ÿฌ๋ฉด ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ ๊ทธ๋ž˜ํ”„๊ฐ€ 2๊ฐœ๋กœ ๋ถ„๋ฆฌ๋œ๋‹ค!

 

๊ทธ๋ฆฌ๊ณ !

import sys
input = sys.stdin.readline

์ฒ˜์Œ์— ํŒŒ์ด์ฌ์œผ๋กœ ์ œ์ถœํ–ˆ๋”๋‹ˆ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚˜์„œ stdin.readline์„ ์‚ฌ์šฉํ–ˆ๋”๋‹ˆ ํ†ต๊ณผํ•จ!

(๋˜‘๊ฐ™์€ ์ฝ”๋“œ pypy๋กœ ๋‚ด๋ฉด ํ†ต๊ณผํ•จ)

 

 

โœ… 10-07 ์ถ”๊ฐ€

์ด ๋ฌธ์ œ๋Š” ์•„๋‹ˆ์—ˆ๊ณ  ํฌ๋ฃจ์Šค์นผ ์จ์„œ ํ’€์—ˆ๋˜ ๋‹ค๋ฅธ ๋ฌธ์ œ์˜€์ง€๋งŒ! (์ฝ”ํ…Œ์˜€๊ธฐ ๋•Œ๋ฌธ์— ๋ฌธ์ œ๋Š” ์•ˆ ์˜ฌ๋ฆผ)

๊ฐ„์„ ์˜ ๊ฐฏ์ˆ˜๊ฐ€ E๊ณ , ๋…ธ๋“œ์˜ ๊ฐฏ์ˆ˜๊ฐ€ V๋ผ๊ณ  ํ•  ๋•Œ ์‹œ๊ฐ„๋ณต์žก๋„๋Š” O(E*logV) ๋ผ๊ณ  ํ•œ๋‹ค. ํ•˜๋งˆํ„ฐ๋ฉด ๋‚˜ ๋…ธ๋ฒจ์ƒ ๋ฐ›์„๋ป”...ใ… ใ… ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹

์‹œ๊ฐ„๋ณต์žก๋„๋„ ์‹ ๊ฒฝ์จ๊ฐ€๋ฉด์„œ ํ’€์–ด์•ผ๊ฒ ๋‹ค๋Š” ๋‹ค์ง!๐Ÿ˜‚

 

 

๐Ÿ™‹‍โ™€๏ธ ์ž‘์„ฑํ•œ ์ฝ”๋“œ

๋”๋ณด๊ธฐ
import sys

def backjoon1647():
  input = sys.stdin.readline

  #๋ถ€๋ชจ๋…ธ๋“œ ํ™•์ธ
  def find_parent(parent, x):
    if parent[x] != x:
      parent[x] = find_parent(parent, parent[x])
    return parent[x]

  #ํ•ฉ์น˜๊ธฐ
  def union_parent(parent, x, y):
    x = find_parent(parent, x)
    y = find_parent(parent, y)
    if x < y:
      parent[y] = x
    else:
      parent[x] = y

  #์ž…๋ ฅ๋ฐ›๋Š” ๋ถ€๋ถ„
  n, m = map(int, input().split())
  graph = []
  for i in range(m):
    a, b, c = map(int, input().split())
    graph.append( (c, a, b) ) #cost๋กœ ์ •๋ ฌํ•˜๋ ค๊ณ 

  #๋ถ€๋ชจ๋…ธ๋“œ ์ƒ์„ฑ ํ›„ ์ž๊ธฐ์ž์‹ ์œผ๋กœ ์„ค์ •
  parent = [0] * (n+1)
  for i in range(n+1):
    parent[i] = i

  graph.sort() #๋น„์šฉ ์ˆœ์„œ๋กœ ์ •๋ ฌ

  lastCost = 0 #๋งˆ์ง€๋ง‰ ๊ฐ„์„  (๋‚˜์ค‘์— ๋นผ๋ ค๊ณ )
  result = 0

  for c,a,b in graph:
    if find_parent(parent, a) != find_parent(parent, b):
      union_parent(parent, a, b)
      result += c
      lastCost = c
  answer = result - lastCost
  print(answer)

 

๋Œ“๊ธ€