[C#] ๋ถ„๋ฆฌ ์ง‘ํ•ฉ

์—…๋ฐ์ดํŠธ:

์นดํ…Œ๊ณ ๋ฆฌ:

ํƒœ๊ทธ: ,


๋ถ„๋ฆฌ ์ง‘ํ•ฉ



๋ถ„๋ฆฌ ์ง‘ํ•ฉ

์„œ๋กœ ์ค‘๋ณต๋˜์ง€ ์•Š๋Š” ๋ถ€๋ถ„ ์ง‘ํ•ฉ๋“ค๋กœ ๋‚˜๋ˆ„์–ด์ง„ ์›์†Œ๋“ค์„ ๊ด€๋ฆฌํ•˜๋Š” ์ž๋ฃŒ๊ตฌ์กฐ.
์ง‘ํ•ฉ์˜ ํ•ฉ์น˜๊ธฐ(Union), ๊ฐ™์€ ์ง‘ํ•ฉ์ธ์ง€ ํ™•์ธ(Find) ์—ฐ์‚ฐ์„ ์ˆ˜ํ–‰
์—ฌ๋Ÿฌ ๊ฐœ์˜ ๊ทธ๋ฃน ์ค‘ ๋‘ ์›์†Œ๊ฐ€ ๊ฐ™์€ ๊ทธ๋ฃน์— ์†ํ•˜๋Š”์ง€ ํ™•์ธ, ๋‘ ๊ทธ๋ฃน์„ ํ•ฉ์น˜๋Š” ์—ฐ์‚ฐ์„ ์ˆ˜ํ–‰.





์˜ˆ์‹œ ๋ฌธ์ œ

1717 ์ค„์„ธ์šฐ๊ธฐ
n, m ์ž…๋ ฅ n+1๊ฐœ์˜ ์ง‘ํ•ฉ, m๊ฐœ์˜ ์—ฐ์‚ฐ ์ˆ˜
์—ฐ์‚ฐ ( x a b)
x = 0 ์ด๋ฉด a, b๋ฅผ ํ•ฉ์น˜๊ธฐ
x = 1 ์ด๋ฉด a, b ๊ฐ™์€ ์ง‘ํ•ฉ์ธ์ง€ ํ™•์ธ


Find, Union
Find(x) - ์›์†Œ x๊ฐ€ ์†ํ•œ ์ง‘ํ•ฉ์˜ ๋Œ€ํ‘œ๋ฅผ ์ฐพ์Œ.
Union(x, y) - ์›์†Œ x๊ฐ€ ์†ํ•œ ์ง‘ํ•ฉ๊ณผ y๊ฐ€ ์†ํ•œ ์ง‘ํ•ฉ์„ ํ•ฉ์นจ.


๋ถ„๋ฆฌ์ง‘ํ•ฉ ์ฝ”๋“œ
class Program
{
    static StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
    static int[] parent;

    static void Main()
    {
        int[] nm = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
        int n = nm[0];
        int m = nm[1];

        parent = new int[n + 1];

        for (int i = 0; i <= n; i++)
        {
            parent[i] = i;
        }

        for (int i = 0; i < m; i++) 
        {
            int[] input = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
            int com = input[0];
            int a = input[1];
            int b = input[2];
            if (com==1)
            {
                if (Find(a)==Find(b))
                {
                    sw.WriteLine("YES");
                }
                else
                {
                    sw.WriteLine("NO");
                }
            }
            else
            {
                Union(a, b);
                sw.WriteLine(string.Join(" ", parent));
            }
        }

        sw.Flush(); sw.Close();
    }

    static int Find(int x)
    {
        if (parent[x] !=x)
        {
            parent[x] = Find(parent[x]);
        }
        return parent[x];
    }

    static void Union(int a, int b) 
    {
        a = Find(a);
        b = Find(b);

        if (a!=b)
        {
            if (a < b)
            {
                parent[b] = a;
            }else
            {
                parent[a] = b;
            }
        }
    }
}




๋ถ„๋ฆฌ์ง‘ํ•ฉ ์‹คํ–‰ ์˜ˆ์‹œ

n = 6 m = 5 ์‹คํ–‰ ์˜ˆ์‹œ

๋ถ„๋ฆฌ์ง‘ํ•ฉ ์‹คํ–‰ ์˜ˆ์‹œ
n = 6 (1 2 3 4 5 6)  
m = 5 (์—ฐ์‚ฐ์˜ ๊ฐœ์ˆ˜)  

0 1 2 ->  1 1 3 4 5 6  parent[2] = 1;   
0 2 3 ->  1 1 1 4 5 6  parent[3] = 1;
0 5 6 ->  1 1 1 4 5 5  parent[6] = 5;
0 3 6 ->  1 1 1 4 1 5  parent[parent[6]] = parnet[3]; 
                       parent[5]         = 1;
1 1 3 ->  "YES"


----------------------------------------------------------
1. 0 1 2
1
 \
  2  3  4  5  6

2. 0 2 3
  1
 / \
2   3  4  5  6

3. 0 5 6
  1       5
 / \       \
2   3  4    6

4. 0 3 6
  1       
 / \      
2   3       4  
    |
    5
     \
      6
  • (1,2,3,5,6), (4)







๋ฉ”๋ชจ


๐Ÿ“”

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ