1 minute read

๐Ÿ“– ์ตœ์†Œ ์‹ ์žฅ ํŠธ๋ฆฌ(MST)

๐Ÿ„ ์‹ ์žฅ ํŠธ๋ฆฌ(Spanning Tree)

  • ์—ฐ๊ฒฐ ๊ทธ๋ž˜ํ”„์—์„œ ๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰์„ ํ†ตํ•ด์„œ ์ƒ๊ธฐ๋Š” ํŠธ๋ฆฌ ์—ฃ์ง€๋กœ ์ด๋ฃจ์–ด์ง„ ์‚ฌ์ดํด์„ ๊ฐ–์ง€ ์•Š๋Š” ์ตœ์†Œ ๋ถ€๋ถ„ ๊ทธ๋ž˜ํ”„๋ฅผ ์˜๋ฏธํ•œ๋‹ค.
  • ๊ทธ๋ž˜ํ”„์˜ ๋ชจ๋“  ์ •์ ์ด ์„œ๋กœ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ์œผ๋ฉด์„œ, ์ˆœํ™˜๊ตฌ์กฐ๊ฐ€ ๋ฐ˜๋ณต๋˜์ง€ ์•Š๋Š”๋‹ค.
  • ์ตœ์†Œ ๋ถ€๋ถ„์ด๋ž€ - ๋ชจ๋“  ์ •์ ์„ ํฌํ•จํ•˜๊ณ , ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ : ์ •์ ์˜ ๊ฐœ์ˆ˜ -1

๐Ÿ„ ์ตœ์†Œ ์‹ ์žฅ ํŠธ๋ฆฌ(MST, Minimum Spanning Tree)

  • ์ตœ์†Œ ์‹ ์žฅ ํŠธ๋ฆฌ๋ž€ Spanning Tree์ค‘์—์„œ ์‚ฌ์šฉ๋œ ๊ฐ€์ค‘์น˜์˜ ๊ฐ’์ด ์ตœ์†Œ์ธ ํŠธ๋ฆฌ์ด๋‹ค.

image

์œ„์™€ ๊ฐ™์ด ๊ฐ ๊ฐ„์„ ๋“ค์˜ ๊ธธ์ด์˜ ํ•ฉ์˜ ์ตœ์†Œ๊ฐ€ ๋˜๋Š” ์—ฐ๊ฒฐ ํŠธ๋ฆฌ๊ฐ€ MST์ด๋‹ค.
์ด๋ฅผ ๊ตฌํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” 2๊ฐ€์ง€ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด ์žˆ๋‹ค.

  • Prim MST ์•Œ๊ณ ๋ฆฌ์ฆ˜ (๋‹จ๊ณ„์  ํ™•์žฅ)
  • Kruskal MSt ์•Œ๊ณ ๋ฆฌ์ฆ˜ (Greedy)


๐Ÿ„ Prim MST

  • Tree ์™€ NotTree๋ฅผ ๊ตฌ๋ถ„ํ•˜์—ฌ ์ •์ ์„ ํ•œ ๊ฐœ์”ฉ ์ถ”๊ฐ€ํ•ด๊ฐ€๋ฉด์„œ T๋ฅผ ์ฑ„์›Œ๋‚˜๊ฐ„๋‹ค.


๐Ÿ„ Kruskal MST

๊ทธ๋ฆฌ๋”” ์•Œ๊ณ ๋ฆฌ์ฆ˜์˜ ์ผ์ข…์œผ๋กœ ๋ณดํ†ต ์ตœ์†Œ ํž™์„ ์ด์šฉํ•˜์—ฌ ๊ตฌํ•œ๋‹ค.
๋ชจ๋“  ๊ทธ๋ž˜ํ”„ ์ •์ ์„ ์ตœ์†Œํž™์— ๋„ฃ์Œ์œผ๋กœ์จ ์‹œ์ž‘ํ•œ๋‹ค.

  • ์‹œ๊ฐ„๋ณต์žก๋„ : O(ElogE)

image

image

๐Ÿ•ธ 4๋ฒˆ์˜ ์‚ฌ์ดํด ํŒ๋‹จ - Union & Find ํ™œ์šฉ

Union-Find

  • ์„œ๋กœ์†Œ ์ง‘ํ•ฉ์„ ํ‘œํ˜„ํ•  ๋•Œ ์‚ฌ์šฉํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜

3๊ฐ€์ง€ ์—ฐ์‚ฐ

  • make-set(x)
    • ์ดˆ๊ธฐํ™”, arr[i] = i
  • union(x, y)
    • ํ•ฉ์น˜๊ธฐ
    • x, y๊ฐ€ ์†ํ•œ ์ง‘ํ•ฉ์„ ํ•ฉ์น˜๋Š” ๊ณผ์ •, ์ผ๋ฐ˜์ ์œผ๋กœ parent = x, child = y
    • O(N)
  • find(x)
    • ์ฐพ๊ธฐ, x๊ฐ€ ์†ํ•œ ์ง‘ํ•ฉ์˜ ์ตœ์ƒ์œ„ ๋…ธ๋“œ ๋ฐ˜ํ™˜
    • O(N-1), ํŠธ๋ฆฌ์˜ ๋†’์ด์™€ ์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ ๋™์ผํ•˜๋‹ค.
    • ๊ฒฝ๋กœ ์••์ถ•ํ•œ ๊ฒฝ์šฐ ์ƒ์ˆ˜ ์‹œ๊ฐ„
union-find ์ฝ”๋“œ ๊ตฌํ˜„
#### make(){
  for(int i=0; i < N; i++){
    root[i] = i;
  }
}

union(x, y)

boolean union(int from, int to){
  int fromRoot = find(from);
  int toRoot = find(to);

  if(fromRoot == toRoot) return false;
  else root[toRoot] = fromRoot;
  return true;
}

find(x)

int find(int x){
  if(root[x] == x) {
    return x;
  } else{
    return find(root[x]); // ์žฌ๊ท€๋ฅผ ์ด์šฉํ•˜๋Š” ๋ฐฉ์‹
    return root[x] = find(root[x]);
  }
}


๐Ÿ„ ํฌ๋ฃจ์Šค์ปฌ vs ํ”„๋ฆผ

ํ”„๋ฆผ์˜ ์‹œ๊ฐ„๋ณต์žก๋„ : O( E log(V)) ํฌ๋ฃจ์Šค์นผ์˜ ์‹œ๊ฐ„๋ณต์žก๋„ : O( E log(E)) ์ฆ‰, ๊ทธ๋ž˜ํ”„ ๋‚ด์˜ ๊ฐ„์„ ์ด ๋งŽ์€ ๊ฒฝ์šฐ - ํ”„๋ฆผ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ฐ„์„ ์ด ์ ์€ ๊ฒฝ์šฐ - ํฌ๋ฃจ์Šค์นผ ์•Œ๊ณ ๋ฆฌ์ฆ˜


๐Ÿ”— ๊ด€๋ จ ์˜ˆ์‹œ

tag:MST



๊ฐœ์ธ ๊ณต๋ถ€ ๊ธฐ๋ก์šฉ ๋ธ”๋กœ๊ทธ์ž…๋‹ˆ๋‹ค.
ํ‹€๋ฆฌ๊ฑฐ๋‚˜ ์˜ค๋ฅ˜๊ฐ€ ์žˆ์„ ๊ฒฝ์šฐ ์ œ๋ณดํ•ด์ฃผ์‹œ๋ฉด ๊ฐ์‚ฌํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.๐Ÿ˜