• hdu1232


    hdu1232

    畅通工程

    0x00 Tags

    并查集

    0x01 题目简介

    统计总的根节点个数ans,然后减1就是结果

    0x02 代码

    #include<bits/stdc++.h>
    
    using namespace std;
    
    
    const int maxn = 1010;
    
    int root[maxn];
    
    
    void Init()
    {
    	for (int i = 1; i < maxn; i++)
    	{
    		root[i] = i;
    	}
    }
    
    /*
    
    未优化的查找
    
    int Find(int x)
    {
    	//return x == root[x] ? x : Find(root[x]);
    
    	while (x != root[x])
    	{
    		x = root[x];
    	}
    
    	return x;
    }
    
    */
    
    
    int Find(int x)
    {
    	//return x == root[x] ? x : Find(root[x]);
    
    	int r = x;
    
    	while (r != root[r])
    	{
    		r = root[r];
    	}
    
    	int i = x, j;
    	while (i != r)
    	{
    		j = root[i];
    		root[i] = r;
    		i = j;
    	}
    
    	return r;
    }
    
    
    void Union(int x, int y)
    {
    	x = Find(x);
    	y = Find(y);
    
    	if (x != y) root[x] = y;
    }
    
    
    
    int main()
    {
    	
    	int n, m;
    	while (scanf("%d", &n) != EOF)
    	{
    		if (n == 0) break;
    
    		Init();
    
    		int s, t;
    
    		scanf("%d", &m);
    
    		for (int i = 1; i <= m; i++)
    		{
    			scanf("%d%d", &s, &t);
    			Union(s, t);
    		}
    
    		// 找出连通分量的个数
    		int num = 0;
    
    		for (int i = 1; i <= n; i++)
    		{
    			if (root[i] == i)
    				num++;
    
    		}
    
    		printf("%d
    ", num - 1);
    	}
    
    	return 0;
    }
    
  • 相关阅读:
    代码互改
    第一次个人编程作业
    第一次博客
    个人总结
    第三次个人作业--用例图设计
    第二次结对作业
    第一次结对作业
    记录浏览他人代码
    中文编程作业
    第一篇随笔
  • 原文地址:https://www.cnblogs.com/LQ6H/p/12940540.html
Copyright © 2020-2023  润新知