[C#] ๋ถ๋ฆฌ ์งํฉ
์นดํ ๊ณ ๋ฆฌ: Til
๋ถ๋ฆฌ ์งํฉ
๋ถ๋ฆฌ ์งํฉ
์๋ก ์ค๋ณต๋์ง ์๋ ๋ถ๋ถ ์งํฉ๋ค๋ก ๋๋์ด์ง ์์๋ค์ ๊ด๋ฆฌํ๋ ์๋ฃ๊ตฌ์กฐ.
์งํฉ์ ํฉ์น๊ธฐ(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)
๋๊ธ๋จ๊ธฐ๊ธฐ