SOJ 1350. Piggy banks

来源:互联网 发布:苹果a1431支持什么网络 编辑:程序博客网 时间:2024/05/17 09:38

题目做多了,就会总结出一些共识。比如说初始化要严谨啊...................................................................

Description

Byteazar the Dragon has N 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.   

Task  

Write 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.  
Input

注意:输入包含多个测试数据。

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+1st line contains a single integer - the number of the piggy bank in which the ith key has been placed. 

Output
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.  
Sample Input
 Copy sample input to clipboard
42124
Sample Output
2(In the foregoing example piggy banks 1 and 4 have to be smashed.)


#include <iostream>#include <vector>#include <queue>#include <stdio.h>#include <cstdlib>#include <memory.h>using namespace std;struct node{    int color;    int father;    /* data */};int N;int coun;void process(node *bank){    for (int i = 1; i <= N; ++i)    {        /* code */        int color=i;        if(bank[i].color>0)            continue;        int curr=i;        while(bank[curr].color==0)        {            bank[curr].color=color;            curr=bank[curr].father;            if(bank[curr].color==color)            {                coun++;                break;            }        }    }}int main(){       while(scanf("%d",&N) != EOF)    {        node *bank=new node[N+1];        for (int i = 1; i <= N; ++i)        {            /* code */            bank[i].color=0;            bank[i].father=0;// initalization first is wrong        }       for (int i = 1; i <=N; ++i)       {          cin>>bank[i].father;       }       coun=0;       process(bank);       cout<<coun<<endl;    }   return 0;}
是不是要去看下染色问题??这个问题本意是说钥匙在哪个房间里面....也就是求图中一共有几个环的问题。

原创粉丝点击