poj 2524 Ubiquitous Religions

简介: 点击打开链接poj 2524 思路:简单的并查集 分析:输入的时候把相同集合的元素合并在一起,那么我们用一个vis数组来标记集合根节点是否出现过。

点击打开链接poj 2524


思路:简单的并查集

分析:输入的时候把相同集合的元素合并在一起,那么我们用一个vis数组来标记集合根节点是否出现过。比如某个几个的根节点为5,那么就把vis[5] = 1。这样最后我们只需要

枚举一变所有的点,把最后有个根节点求出来就是最大的集合数量


代码:

#include<set>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

const int MAXN = 50010;

int father[MAXN];

void init(int n){
    for(int i = 0 ; i <= n ; i++)
        father[i] = i;
}

int find(int x){
    if(father[x] != x)
        father[x] = find(father[x]);
    return father[x];
}

void solve(int x , int y){
    int fx = find(x);
    int fy = find(y);
    if(fx != fy)
       father[fx] = fy;
}

int main(){
    int cas = 1;
    int n , m;
    int x , y;
    while(scanf("%d%d" , &n , &m) && n+m){
        init(n);
        while(m--){
            scanf("%d%d" , &x , &y); 
            solve(x , y);
        }
        set<int>s;
        for(int i = 1 ; i <= n ; i++)
            s.insert(find(i));
        printf("Case %d: %d\n" , cas++ , s.size());
    }
    return 0;
}



目录
相关文章
|
9月前
poj-1611-The Suspects
poj-1611-The Suspects
41 0
POJ 1804
题目:http://poj.org/problem?id=1804 大意:给你一串数字,排序。求出最少的交换次数  \ 我用归并做的 #include #include using namespace std; int aa[500010],bb[500010]; long lon...
710 0
POJ 2262 Goldbach&#39;s Conjecture
Problem Description In 1742, Christian Goldbach, a German amateur mathematician, sent a letter to Leonhard Euler in which he made the foll...
1025 0
|
机器学习/深度学习 算法
|
人工智能 vr&ar
|
算法 数据建模 机器学习/深度学习
poj1273Drainage Ditches
1 #include 2 /* 3 题意:就是寻找从源点到汇点的最大流! 4 要注意的是每两个点的流量可能有多个,也就是说有重边,所以要把两个点的所有的流量都加起来 5 就是这两个点之间的流量了! 6 ...
862 0
|
存储
大数加法-poj-1503
poj-1503-Integer Inquiry Description One of the first users of BIT's new supercomputer was Chip Diller. He extended his exploration of powers of 3 to go from 0 to 333 and he explored taking vari
1126 0
|
算法 存储
POJ 1014 Dividing 解答
题目详见http://poj.org/problem?id=1014 看到这道题第一反应便知道它是一道类似背包问题的题,  解法我自然而然得从背包问题的解法入手,  网上查了查,  背包问题的基本题型是01背包, 即每种...
1062 0