zoukankan      html  css  js  c++  java
  • CodeForces 755C PolandBall and Forest (并查集)

    题意:给定n个数,Ai的下标为1~n。对于每一个i,Ai与i在同一个树上,且是与i最远的点中id最小的点(这个条件变相的说明i与Ai连通)。求森林中树的个数。

    分析:若i与Ai连通,则在同一个树上,因此连通块的个数就是树的个数。并查集即可。

    #pragma comment(linker, "/STACK:102400000, 102400000")
    #include<cstdio>
    #include<cstring>
    #include<cstdlib>
    #include<cctype>
    #include<cmath>
    #include<iostream>
    #include<sstream>
    #include<iterator>
    #include<algorithm>
    #include<string>
    #include<vector>
    #include<set>
    #include<map>
    #include<stack>
    #include<deque>
    #include<queue>
    #include<list>
    #define Min(a, b) ((a < b) ? a : b)
    #define Max(a, b) ((a < b) ? b : a)
    typedef long long ll;
    typedef unsigned long long llu;
    const int INT_INF = 0x3f3f3f3f;
    const int INT_M_INF = 0x7f7f7f7f;
    const ll LL_INF = 0x3f3f3f3f3f3f3f3f;
    const ll LL_M_INF = 0x7f7f7f7f7f7f7f7f;
    const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
    const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
    const int MOD = 1e9 + 7;
    const double pi = acos(-1.0);
    const double eps = 1e-8;
    const int MAXN = 10000 + 10;
    const int MAXT = 10000 + 10;
    using namespace std;
    int fa[MAXN];
    int a[MAXN];
    set<int> s;
    int Find(int v){
        return fa[v] = (fa[v] == v) ? v : Find(fa[v]);
    }
    int main(){
        for(int i = 0; i < MAXN; ++i){
            fa[i] = i;
        }
        int n;
        scanf("%d", &n);
        for(int i = 1; i <= n; ++i){
            scanf("%d", &a[i]);
            int tx = Find(i);
            int ty = Find(a[i]);
            if(tx < ty) fa[ty] = tx;
            else fa[tx] = ty;
        }
        for(int i = 1; i <= n; ++i){
            if(Find(i) == i) s.insert(i);
            if(Find(a[i]) == a[i]) s.insert(a[i]);
        }
        printf("%d\n", s.size());
        return 0;
    }
  • 相关阅读:
    关于idea的目录, mybatis里mapper无法用resource获取 和 驼峰命令规则
    直接调用类方法 和 new再调用方法 的区别
    腾讯笔试题
    linux安装包
    centos 学习笔记一
    putty链接l虚拟机linux centos
    单链表的一般处理(C语言)
    华为2011机试题
    【转】函数返回类型为指针类型时的一些问题
    在 Windows Server 2012 上安装 dotNET Framework v3.5
  • 原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/6294080.html
Copyright © 2011-2022 走看看