码迷,mamicode.com
首页 > 其他好文 > 详细

poj 2005

时间:2014-11-16 10:30:01      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:des   io   ar   os   sp   for   on   bs   amp   

Description

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

Input

第一行一个整数 N (1 <= N <= 1.000.000) – 表示存钱罐的总数. 接下来每行一个整数,第 i+1行的整数代表第i个存钱罐的钥匙放置的存钱罐编号.

Output

一个整数表示最少打破多少个存钱罐.

Sample Input

4
2
1
2
4

Sample Output


2
In the foregoing example piggy banks 1 and 4 have to be smashed.

 

 

#include<iostream>

#include<cstdio>

#include<cstring>

#include<string>

#include<cmath>

#include<cstdlib>

#include<algorithm>

using namespace std;

const int maxn=1000005;

int n,set[maxn],ans=0;

 

int find(int x)

{

  if(x!=set[x])

  set[x]==find(set[x]);

  return set[x];

}

void combine(int x,int y)

{

  int fx=find(x);

  int fy=find(y);

  if(fx!=fy)

  set[fy]=fx;

}

int main()

{

  scanf("%d",&n);;

  for(int i=1;i<=n;i++)

  set[i]=i;

  for(int i=1;i<=n;i++)

  {

int x;

scanf("%d",&x);

combine(i,x);

    }

for(int i=1;i<=n;i++)

if(set[i]==i)

ans++;

printf("%d\n",ans);

system("pause");

return 0;

poj 2005

标签:des   io   ar   os   sp   for   on   bs   amp   

原文地址:http://www.cnblogs.com/a972290869/p/4101078.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!