zoukankan      html  css  js  c++  java
  • bzoj1529: [POI2005]ska Piggy banks

    传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=1529

    题目大意:Byteazar 有 N 个小猪存钱罐. 每个存钱罐只能用钥匙打开或者砸开. Byteazar 已经把每个存钱罐的钥匙放到了某些存钱罐里. Byteazar 现在想买一台汽车于是要把所有的钱都取出来. 他想尽量少的打破存钱罐取出                  所有的钱,问最少要打破多少个存钱罐.

    题解:并查集

    代码:

     1 #include<iostream>
     2 #include<cstring>
     3 #include<cstdio>
     4 #include<algorithm>
     5 #include<cmath>
     6 #define maxn 1000005
     7 using namespace std;
     8 int n,tot,ans;
     9 int fa[maxn];
    10 int read()
    11 {
    12     int x=0; char ch; bool bo=0;
    13     while (ch=getchar(),ch<'0'||ch>'9') if (ch=='-') bo=1;
    14     while (x=x*10+ch-'0',ch=getchar(),ch>='0'&&ch<='9');
    15     if (bo) return -x; return x;
    16 }
    17 int find(int x)
    18 {
    19     if (fa[x]!=x) fa[x]=find(fa[x]); 
    20     return fa[x];
    21 }
    22 int main()
    23 {
    24     n=read();
    25     for (int i=1; i<=n; i++) fa[i]=i;
    26     for (int i=1; i<=n; i++)
    27     {
    28         int x=read();
    29         int q=find(i),p=find(x);
    30         if (q!=p) fa[q]=p;
    31     }
    32     for (int i=1; i<=n; i++) if (fa[i]==i) ans++;
    33     printf("%d
    ",ans);
    34 }
    View Code
  • 相关阅读:
    poj1459(多源点网络流)
    poj 2480
    poj1850和poj1496(组合数)
    poj3252(组合数)
    hdu1452(逆元)
    因子和与因子个数
    poj 2478(欧拉函数打表)
    p3807(lucas定理)
    F-有趣的数字(组合数+逆元)
    《Java并发编程的艺术》Java并发机制的底层实现原理(二)
  • 原文地址:https://www.cnblogs.com/HQHQ/p/5578217.html
Copyright © 2011-2022 走看看