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
  • 相关阅读:
    Linq-单条数据删除
    斐波那契额数列及青蛙跳台阶问题
    旋转数组的最小数字
    扑克牌的顺子
    qsort(),sort()排序函数
    从尾到头打印链表
    查找链表中倒数第k个结点
    左旋转字符串
    数组前半部分和后半部分有序的全排序
    二元树中和为某一值的所有路径
  • 原文地址:https://www.cnblogs.com/HQHQ/p/5578217.html
Copyright © 2011-2022 走看看