洛谷P3420 SKA-Piggy Banks(并查集判环)

版权声明:如果路过的各位大佬想对菜鸡进行指点请加QQ:3360769137 https://blog.csdn.net/PleasantlY1/article/details/83386350

Byteazar the Dragon has NNN piggy banks. Each piggy bank can either be opened with its corresponding key or smashed. Byteazar has put the keys in some of the piggy banks - he remembers which key has been placed in which piggy bank. Byteazar intends to buy a car and needs to gain access to all of the piggy banks. However, he wants to destroy as few of them as possible. Help Byteazar to determine how many piggy banks have to be smashed.

TaskWrite a programme which:

reads from the standard input the number of piggy banks and the deployment of their corresponding keys,finds the minimal number of piggy banks to be smashed in order to gain access to all of them,writes the outcome to the standard output.

Byteazar the Dragon拥有N个小猪存钱罐。每一个存钱罐能够用相应的钥匙打开或者被砸开。Byteazar已经将钥匙放入到一些存钱罐中。现在已知每个钥匙所在的存钱罐,Byteazar想要买一辆小汽车,而且需要打开所有的存钱罐。然而,他想要破坏尽量少的存钱罐,帮助Byteazar去决策最少要破坏多少存钱罐。

任务:

写一段程序包括:

读入存钱罐的数量以及相应的钥匙的位置,求出能打开所有存钱罐的情况下,需要破坏的存钱罐的最少数量并将其输出。

输入输出格式

输入格式:

The first line of the standard input contains a single integer N (1≤N≤1 000 000) - this is the number of piggy banks owned by the dragon. The piggy banks (as well as their corresponding keys) are numbered from 1 to N. Next, there are N lines: the (i+1)'st line contains a single integer - the number of the piggy bank in which the i'th key has been placed.

第一行:包括一个整数N(1<=N<=1000000),这是Byteazar the Dragon拥有的存钱罐的数量。

存钱罐(包括它们对应的钥匙)从1到N编号。

接下来有N行:第i+1行包括一个整数x,表示第i个存钱罐对应的钥匙放置在了第x个存钱罐中。

输出格式:

The first and only line of the standard output should contain a single integer - the minimal number of piggy banks to be smashed in order to gain access to all of the piggy banks.

仅一行:包括一个整数,表示能打开所有存钱罐的情况下,需要破坏的存钱罐的最少数量。

输入输出样例

输入样例#1: 

4
2
1
2
4

输出样例#1: 

2

思路:读完题第一个反应是联通块,考虑了一下爆搜,然后注意到了联通块成环的情况,就发现,只需要判环的数量+非环的数量即可。通过并查集实现,初始化指向本身,有环时+1。(因为每个罐子都有指向,所以不必考虑单点)

代码如下:

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int p[1000005],sum=0;
int find(int x)
{
    int r=x;
    while(r!=p[r])
    {
        r=p[r];
    }
    int i=x,j;
    while(i!=r)
    {
        j=p[i];
        p[i]=r;
        i=j;
    }
    return r;
}
void bin(int x,int y)
{
    int tx,ty;
    tx=find(x);
    ty=find(y);
    if(tx!=ty) p[ty]=tx;
    else sum++;
}
int main()
{
    int n;
    cin>>n;
    sum=0;
    for(int i=1;i<=n;++i) p[i]=i;
    for(int i=1;i<=n;++i)
    {
        int xx;
        cin>>xx;
        bin(i,xx);
    }
    cout<<sum<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/PleasantlY1/article/details/83386350
今日推荐