zoukankan      html  css  js  c++  java
  • A1118 Birds in Forest [并查集]

    在这里插入图片描述

    #include<iostream>
    #include<vector>
    #include<map>
    #include<string>
    #include<cstring>
    #include<cstdio>
    #include<algorithm>
    using namespace std;
    const int maxn = 10002;
    int father[maxn], cnt[maxn];
    int getfather(int x)
    {
    	int a = x;
    	while (x != father[x])
    		x = father[x];
    	while (a != father[a])
    	{
    		int z = a;
    		a = father[a];
    		father[z] = x;
    	}
    	return x;
    }
    void Union(int a, int b)
    {
    	int fa = getfather(a);
    	int fb = getfather(b);
    	if (fa != fb)
    		father[fa] = fb;
    }
    bool exist[maxn];
    int main()
    {
    	int n, k, temp1, temp2, queryn, treenum = 0, birdsnum = 0;
    	cin >> n;
    	for (int i = 0; i < maxn; i++)
    		father[i] = i;
    	for (int i = 0; i < n; i++)
    	{
    		cin >> k >> temp1;
    		exist[temp1] = true;
    		for (int j = 0; j < k - 1; j++)
    		{
    			cin >> temp2;
    			exist[temp2] = true;
    			Union(temp1, temp2);
    		}
    	}
    	for (int i = 0; i < maxn; i++)
    	{
    		if (exist[i])
    			cnt[getfather(i)]++;
    	}
    	for (int i = 0; i < maxn; i++)
    	{
    		if (cnt[i] != 0)
    		{
    			treenum++;
    			birdsnum += cnt[i];
    		}
    	}
    	cout << treenum << " " << birdsnum << endl;
    	cin >> queryn;
    
    	for (int i = 0; i < queryn; i++)
    	{
    		cin >> temp1 >> temp2;
    		if (getfather(temp1) == getfather(temp2))
    			cout << "Yes" << endl;
    		else
    			cout << "No" << endl;
    	}
    }
    
  • 相关阅读:
    时间与时间戳互换
    原生js鼠标滑动滚轮事件
    php调用whois接口域名查询
    通用php与mysql数据库配置文件
    多个div独立控制其显示/隐藏
    jquery
    定时显示div
    一个清爽的弹出层特效
    自定义百度竞价电话回拨样式总结
    基于h5+ajax实现的手机定位
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13811973.html
Copyright © 2011-2022 走看看