杭电1213

21 篇文章 0 订阅

题目描述:

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.

这题就是典型的并查集(刚刚学会并查集这个概念),即求有几个几个互不相交的集合,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(); 否则读取格式就不对了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值