๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“š Algorithm/Algorithm Note

Union-find ์•Œ๊ณ ๋ฆฌ์ฆ˜ (Disjoint Set), ์„œ๋กœ์†Œ ์ง‘ํ•ฉ

Disjoint Set์ด๋ž€?

์„œ๋กœ ์ค‘๋ณต๋˜์ง€ ์•Š์€ ๋ถ€๋ถ„ ์ง‘ํ•ฉ๋“ค๋กœ ๋‚˜๋ˆ„์–ด์ง„ ์›์†Œ๋“ค์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ์ €์žฅํ•˜๊ณ  ์กฐ์ž‘ํ•˜๋Š” ์ž๋ฃŒ๊ตฌ์กฐ์ด๋‹ค. 

์ƒํ˜ธ ๋ฐฐํƒ€์ ์ธ ๋ถ€๋ถ„ ์ง‘ํ•ฉ๋“ค๋กœ ๋‚˜๋ˆ ์ง„ ์›์†Œ๋“ค์— ๋Œ€ํ•œ ์ž๋ฃŒ๊ตฌ์กฐ๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค.

ํ”ํžˆ ์„œ๋กœ์†Œ ์ง‘ํ•ฉ ์ž๋ฃŒ๊ตฌ์กฐ ๋ผ๊ณ ๋„ ํ•œ๋‹ค. 

 

 

Union-Find ๋ž€?

Union-Find๋Š” ์„œ๋กœ์†Œ ์ง‘ํ•ฉ์„ ํ‘œํ˜„ํ•  ๋•Œ ์‚ฌ์šฉํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด๋‹ค.

์ง‘ํ•ฉ์„ ํ‘œํ˜„ํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ๋Š” ๋ฐฐ์—ด, ์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ ๋“ฑ์„ ์ด์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ๊ทธ ์ค‘ ๊ฐ€์žฅ ํšจ์œจ์ ์ธ ํŠธ๋ฆฌ ๊ตฌ์กฐ๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•œ๋‹ค. 

๋ณดํ†ต MST์˜ ํฌ๋ฃจ์Šค์นผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์—์„œ ์‚ฌ์šฉ๋œ๋‹ค. 

ํŠธ๋ฆฌ๋ฅผ ์ด์šฉํ•œ ์ง‘ํ•ฉ์˜ ์ฒ˜๋ฆฌ
- ๊ฐ™์€ ์ง‘ํ•ฉ์˜ ์›์†Œ๋“ค์€ ํ•˜๋‚˜์˜ ํŠธ๋ฆฌ๋กœ ๊ด€๋ฆฌํ•œ๋‹ค. (์ž์‹ ๋…ธ๋“œ๊ฐ€ ๋ถ€๋ชจ ๋…ธ๋“œ๋ฅผ ๊ฐ€๋ฆฌํ‚ด)
- ํŠธ๋ฆฌ์˜ ๋ฃจํŠธ๋ฅผ ์ง‘ํ•ฉ์˜ ๋Œ€ํ‘œ ์›์†Œ๋กœ ์‚ผ๋Š”๋‹ค. 

 

 

Union-Find ์—ฐ์‚ฐ

  1. Make-Set(x) : ์›์†Œ x๋กœ๋งŒ ์ด๋ฃจ์–ด์ง„ ์ง‘ํ•ฉ์„ ๋งŒ๋“ ๋‹ค.  - ์ดˆ๊ธฐํ™” 
  2. Find-Set(x) : ์›์†Œ x๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ์ง‘ํ•ฉ์„ ์•Œ์•„๋‚ธ๋‹ค. (์ฐพ๋Š”๋‹ค)  - ์ฐพ๊ธฐ
  3. Union(x, y) : ์›์†Œ x๋ฅผ ๊ฐ€์ง„ ์ง‘ํ•ฉ๊ณผ ์›์†Œ y๋ฅผ ๊ฐ€์ง„ ์ง‘ํ•ฉ์˜ ํ•ฉ์ง‘ํ•ฉ  - ํ•ฉํ•˜๊ธฐ

 

 

ํŠธ๋ฆฌ๋ฅผ ์ด์šฉํ•œ ์ง‘ํ•ฉ ์ฒ˜๋ฆฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ 

Make-Set(x) 
{
	p[x] = x;
}

Union(x, y)
{
	p[Find-Set(y)] = Find-Set(x);
}

Find-Set(x)
{
	if(x=p[x])
    	then return x;
        else return Find-Set(p[x]);
}

 

 

Union-Find ๊ณผ์ • 

 

 

Union-Find ๊ธฐ๋ณธ ์ฝ”๋“œ

parents = [i for i in range(SIZE)]


def find(parent, x):
    if parent[x] == x:
        return x

    else:	#๋ถ€๋ชจ ์ฐพ๊ธฐ 
        return find(parent, parent[x])


def union(parent, x, y):
    # ๊ฐ ์›์†Œ๊ฐ€ ์†ํ•œ ํŠธ๋ฆฌ์˜ ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ์ฐพ๊ธฐ.
    fX = find(parent, x)
    fY = find(parent, y)

    parent[fY] = fX

 

 

Union-Find ์—ฐ์‚ฐ ํšจ์œจ ๋†’์ด๋Š” ๋ฐฉ๋ฒ•

๋žญํฌ๋ฅผ ์ด์šฉํ•œ Union

- ๊ฐ ๋…ธ๋“œ๋Š” ์ž์‹ ์„ ๋ฃจํŠธ๋กœ ํ•˜๋Š” ์„œ๋ธŒํŠธ๋ฆฌ์˜ ๋†’์ด๋ฅผ ๋žญํฌ Rank ๋ผ๋Š” ์ด๋ฆ„์œผ๋กœ ์ €์žฅํ•œ๋‹ค. 

- ๋‘ ์ง‘ํ•ฉ์„ ํ•ฉ์น  ๋•Œ ๋žญํฌ๊ฐ€ ๋‚ฎ์€ ์ง‘ํ•ฉ์„ ๋žญํฌ๊ฐ€ ๋†’์€ ์ง‘ํ•ฉ์— ๋ถ™์ธ๋‹ค. 

 

๊ฒฝ๋กœ ์••์ถ•

- Find-Set์„ ํ–‰ํ•˜๋Š” ๊ณผ์ •์—์„œ ๋งŒ๋‚˜๋Š” ๋ชจ๋“  ๋…ธ๋“œ๋“ค์ด ์ง์ ‘ ๋ฃจํŠธ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋„๋ก ํฌ์ธํ„ฐ๋ฅผ ๋ฐ”๊พผ๋‹ค. 

 

 

 

2023.04.04 - [๐Ÿ“š Algorithm/Algorithm Note] - ์•Œ๊ณ ๋ฆฌ์ฆ˜ - ์ตœ์†Œ ์‹ ์žฅ ํŠธ๋ฆฌ(Minimum Spanning Tree), ํฌ๋ฃจ์Šค์นผ(Kruskal), ํ”„๋ฆผ(Prim) Python ์ฝ”๋“œ

 

 

 

 

728x90