题目描述:
Today is Ignatius' birthday. He invites a lot of friends. Now it's dinner time. Ignatius wants to know how many tables he needs at least. You have to notice that not all the friends know each other, and all the friends do not want to stay with strangers.
One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.
For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.
One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.
For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.
这题就是典型的并查集(刚刚学会并查集这个概念),即求有几个几个互不相交的集合,AC代码:
using System;
namespace a1
{
class Program
{
public static int[] a;
//并查集初始化
public static void Init(int n)
{
for (int i = 0; i < n; i++)
a[i] = i;
}
//合并两个元素所在的集合
public static void Union(int x, int y)
{
x = getfather(x);
y = getfather(y);
if (x != y)
a[x] = y;
}
//判断两个元素是否属于同一个集合
public static bool same(int x, int y)
{
return getfather(x) == getfather(y);
}
//获取根结点
public static int getfather(int x)
{
while (x != a[x])
x = a[x];
return x;
}
public static void Main(string[] args)
{
string str = string.Empty;
str = Console.ReadLine();
int t;
t = Convert.ToInt32(str);
while (t-- > 0) {
str = Console.ReadLine();
string[] s = str.Split(' ');
int n = Convert.ToInt32(s[0]), m = Convert.ToInt32(s[1]);
a = new int[n];
Init(n);
while (m-- > 0) {
str = Console.ReadLine();
s = str.Split(' ');
int p = Convert.ToInt32(s[0]) - 1, q = Convert.ToInt32(s[1]) - 1;
if(!same(p,q)) Union(p,q);
}
Console.ReadLine();
int flag=0;
for(int i=0;i<n;i++)
if(a[i]==i) flag++;
Console.WriteLine("{0}",flag);
}
}
}
}
千万不要漏了最后那边的Console.Readline(); 否则读取格式就不对了