Skip to content

Latest commit

ย 

History

History

jo1863

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
ย 
ย 
ย 
ย 
ย 
ย 

[JUNGOL-1863] ์ข…๊ต

image image

union-by-rank (union-by-height)

์ฐธ๊ณ  ์ž๋ฃŒ : [์•Œ๊ณ ๋ฆฌ์ฆ˜] Union-Find ์•Œ๊ณ ๋ฆฌ์ฆ˜

์ด ๋ฌธ์ œ๋Š” union ์—ฐ์‚ฐ์— ๋Œ€ํ•œ ์ตœ์ ํ™”๊ฐ€ ํ•„์š”ํ•œ ๋ฌธ์ œ์ด๋‹ค. union ์—ฐ์‚ฐ์˜ ์ตœ์ ํ™”๋กœ๋Š” union-by-rank๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

ํŠธ๋ฆฌ๋กœ ์—ฐ๊ฒฐํ•  ๋•Œ ์ตœ์•…์˜ ๊ฒฝ์šฐ๋Š” ํŠธ๋ฆฌ์˜ ์žฅ์ ์„ ์ „ํ˜€ ์‚ด๋ฆฌ์ง€ ๋ชปํ•˜๊ณ  ์ผ๋ ฌ๋กœ ์ž๋ฃŒ๊ฐ€ ๊ณ„์† ๋‚˜์—ด๋˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋‹ค. ์ด ๊ฒฝ์šฐ union, find ์—ฐ์‚ฐ ๋ชจ๋‘ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ O(N)์ด ๋˜์–ด๋ฒ„๋ฆฐ๋‹ค. ์ด๋Š” ๋ฐฐ์—ด๋กœ ๊ตฌํ˜„ํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค ๋น„ํšจ์œจ์ ์ด๋‹ค. ๋”ฐ๋ผ์„œ find ์—ฐ์‚ฐ๊ณผ union ์—ฐ์‚ฐ์„ ์ตœ์ ํ™”ํ•ด์ฃผ์–ด์•ผ ํ•˜๋Š”๋ฐ, ๋‚˜๋Š” ๊ทธ๋™์•ˆ find ์—ฐ์‚ฐ ์ตœ์ ํ™”(๊ฒฝ๋กœ ์••์ถ•)๋งŒ ์•Œ๊ณ  ์žˆ์—ˆ๋‹ค. union ์—ฐ์‚ฐ์˜ ์ตœ์ ํ™”์ธ union-by-rank๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๊ตฌํ˜„ํ•œ๋‹ค.

  • rank ๋ฐฐ์—ด์— ํŠธ๋ฆฌ์˜ ๋†’์ด๋ฅผ ์ €์žฅํ•œ๋‹ค.
  • union ์—ฐ์‚ฐ ์‹œ ํ•ญ์ƒ ๋†’์ด๊ฐ€ ๋” ๋‚ฎ์€ ํŠธ๋ฆฌ๋ฅผ ๋†’์€ ํŠธ๋ฆฌ ๋ฐ‘์— ๋„ฃ๋Š”๋‹ค. ์ฆ‰, ๋†’์ด๊ฐ€ ๋” ๋†’์€ ์ชฝ์„ root๋กœ ์‚ผ๋Š”๋‹ค.
  • ๋‘ ํŠธ๋ฆฌ์˜ rank๊ฐ€ ๋™์ผํ•˜์—ฌ ๋†’์ด๊ฐ€ ๋†’์•„์ ธ์•ผ๋งŒ ํ•˜๋Š” ๊ฒฝ์šฐ์—๋Š” union ์—ฐ์‚ฐ ํ›„ ๊ฒฐ๊ณผ ํŠธ๋ฆฌ์˜ rank๋ฅผ 1 ์ฆ๊ฐ€ ์‹œ์ผœ์ค€๋‹ค.
void union(int a, int b) {
    a = find(a);
    b = find(b);

    if (a == b) return;
    if (rank[a] < rank[b]) root[a] = b;
    else {
        root[b] = a;
        if (rank[a] == rank[b]) rank[a] ++;
    }
}

image