728x90
๋ฐ˜์‘ํ˜•

์„œ๋กœ์†Œ ์ง‘ํ•ฉ 2

[์•Œ๊ณ ๋ฆฌ์ฆ˜] ์„œ๋กœ์†Œ ์ง‘ํ•ฉ (Disjoint Sets) - ์‚ฌ์ดํด ํŒ๋ณ„

์„œ๋กœ์†Œ ์ง‘ํ•ฉ์„ ํ™œ์šฉํ•œ ์‚ฌ์ดํด ํŒ๋ณ„ ์„œ๋กœ์†Œ ์ง‘ํ•ฉ์€ ๋ฌด๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„ ๋‚ด์—์„œ์˜ ์‚ฌ์ดํด์„ ํŒ๋ณ„ํ•  ๋•Œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ฐธ๊ณ ๋กœ ๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„์—์„œ์˜ ์‚ฌ์ดํด ์—ฌ๋ถ€๋Š” DFS๋ฅผ ์ด์šฉํ•˜์—ฌ ํŒ๋ณ„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 1. ์‚ฌ์ดํด ํŒ๋ณ„ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ฐ ๊ฐ„์„ ์„ ํ•˜๋‚˜์”ฉ ํ™•์ธํ•˜๋ฉฐ ๋‘ ๋…ธ๋“œ์˜ ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. ๋ฃจํŠธ ๋…ธ๋“œ๊ฐ€ ์„œ๋กœ ๋‹ค๋ฅด๋‹ค๋ฉด ๋‘ ๋…ธ๋“œ์— ๋Œ€ํ•˜์—ฌ ํ•ฉ์ง‘ํ•ฉ(Union) ์—ฐ์‚ฐ์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค. ๋ฃจํŠธ ๋…ธ๋“œ๊ฐ€ ์„œ๋กœ ๊ฐ™๋‹ค๋ฉด ์‚ฌ์ดํด(Cycle)์ด ๋ฐœ์ƒํ•œ ๊ฒƒ์ž…๋‹ˆ๋‹ค. ๊ทธ๋ž˜ํ”„์— ํฌํ•จ๋˜์–ด ์žˆ๋Š” ๋ชจ๋“  ๊ฐ„์„ ์— ๋Œ€ํ•˜์—ฌ 1๋ฒˆ ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค. 2. ๋™์ž‘ ๊ณผ์ • ์‚ดํŽด๋ณด๊ธฐ 3. ์„œ๋กœ์†Œ ์ง‘ํ•ฉ์„ ํ™œ์šฉํ•œ ์‚ฌ์ดํด ํŒ๋ณ„ (์ฝ”๋“œ) 1) ์„œ๋กœ์†Œ ์ง‘ํ•ฉ์„ ํ™œ์šฉํ•œ ์‚ฌ์ดํด ํŒ๋ณ„ (Python) # ํŠน์ • ์›์†Œ๊ฐ€ ์†ํ•œ ์ง‘ํ•ฉ์„ ์ฐพ๊ธฐ def find_parent(parent, x): #..

Algorithm 2023.12.10

[์•Œ๊ณ ๋ฆฌ์ฆ˜] ์„œ๋กœ์†Œ ์ง‘ํ•ฉ (Disjoint Sets) - ์ž๋ฃŒ๊ตฌ์กฐ

๊ทธ๋ž˜ํ”„ ๊ทธ๋ž˜ํ”„(Graph)๋ž€ ๋…ธ๋“œ์™€ ๋…ธ๋“œ ์‚ฌ์ด์— ์—ฐ๊ฒฐ๋œ ๊ฐ„์„ ์˜ ์ •๋ณด๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์˜๋ฏธํ•œ๋‹ค. ์„œ๋กœ์†Œ ์ง‘ํ•ฉ ์„œ๋กœ์†Œ ์ง‘ํ•ฉ(Disjoint Sets)์ด๋ž€ ๊ณตํ†ต ์›์†Œ๊ฐ€ ์—†๋Š” ๋‘ ์ง‘ํ•ฉ์„ ์˜๋ฏธํ•œ๋‹ค. ์„œ๋กœ์†Œ ์ง‘ํ•ฉ ์ž๋ฃŒ๊ตฌ์กฐ ์„œ๋กœ์†Œ ๋ถ€๋ถ„ ์ง‘ํ•ฉ๋“ค๋กœ ๋‚˜๋ˆ„์–ด์ง„ ์›์†Œ๋“ค์˜ ๋ฐ์ดํ„ฐ๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•œ ์ž๋ฃŒ๊ตฌ์กฐ์ด๋‹ค. ์„œ๋กœ์†Œ ์ง‘ํ•ฉ ์ž๋ฃŒ๊ตฌ์กฐ๋Š” ๋‘ ์ข…๋ฅ˜์˜ ์—ฐ์‚ฐ์„ ์ง€์›ํ•œ๋‹ค. ํ•ฉ์ง‘ํ•ฉ(Union): ๋‘ ๊ฐœ์˜ ์›์†Œ๊ฐ€ ํฌํ•จ๋œ ์ง‘ํ•ฉ์„ ํ•˜๋‚˜์˜ ์ง‘ํ•ฉ์œผ๋กœ ํ•ฉ์น˜๋Š” ์—ฐ์‚ฐ์ด๋‹ค. ์ฐพ๊ธฐ(Find): ํŠน์ •ํ•œ ์›์†Œ๊ฐ€ ์†ํ•œ ์ง‘ํ•ฉ์ด ์–ด๋–ค ์ง‘ํ•ฉ์ธ์ง€ ์•Œ๋ ค์ฃผ๋Š” ์—ฐ์‚ฐ์ด๋‹ค. ์„œ๋กœ์†Œ ์ง‘ํ•ฉ ์ž๋ฃŒ๊ตฌ์กฐ๋Š” ํ•ฉ์น˜๊ธฐ ์ฐพ๊ธฐ(Union Find) ์ž๋ฃŒ๊ตฌ์กฐ๋ผ๊ณ  ๋ถˆ๋ฆฌ๊ธฐ๋„ ํ•œ๋‹ค. 1. ์—ฌ๋Ÿฌ ๊ฐœ์˜ ํ•ฉ์น˜๊ธฐ ์—ฐ์‚ฐ์ด ์ฃผ์–ด์กŒ์„ ๋•Œ ์„œ๋กœ์†Œ ์ง‘ํ•ฉ ์ž๋ฃŒ๊ตฌ์กฐ์˜ ๋™์ž‘ ๊ณผ์ • ํ•ฉ์ง‘ํ•ฉ(Union) ์—ฐ์‚ฐ์„ ํ™•์ธํ•˜์—ฌ,..

Algorithm 2023.12.09
728x90
๋ฐ˜์‘ํ˜•