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
  • 相关阅读:
    requirejs学习笔记
    Java日期时间处理
    Linux安装ftp服务
    软考真题之设计模式
    《Microsoft Visio 2013 Step by Step.pdf》
    《C++实践之路.pdf》源码
    Python基础与进阶
    微信小程序实战[01]
    常用资源网站
    ECLIPS-S测井系统下的仪器挂接 [CV模块]
  • 原文地址:https://www.cnblogs.com/HQHQ/p/5578217.html
Copyright © 2011-2022 走看看