AtCoder Contest 228 B - Takahashi‘s Secret

Problem Statement

Takahashi has NN friends. They have nicknames: Friend 11, Friend 22, \ldots…, Friend NN.

One day, Takahashi accidentally let one of his friends, Friend XX, learn his shameful secret.
For each i = 1, 2, \ldots, Ni=1,2,…,N, when Friend ii learns the secret, he/she will share it with Friend A_iAi​, if Friend A_iAi​ has not already learned it.

How many of Takahashi's friends will learn the secret in the end?

Constraints

  • 2 \leq N \leq 10^52≤N≤105
  • 1 \leq X \leq N1≤X≤N
  • 1 \leq A_i \leq N1≤Ai​≤N
  • A_i \neq iAi​=i
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

NN XX
A_1A1​ A_2A2​ \cdots⋯ A_NAN​

Output

Print the answer.


Sample Input 1 Copy

Copy

4 2
3 1 1 2

Sample Output 1 Copy

Copy

3

Takahashi's secret will be learned by Friend 11, Friend 22, and Friend 33, as follows.

  • One day, Takahashi let Friend 22 learn the secret.
  • Friend 22 shares it with Friend 11.
  • Friend 11 shares it with Friend 33.

In the end, three of his friends learn the secret, so we print 33.


Sample Input 2 Copy

Copy

20 12
7 11 10 1 7 20 14 2 17 3 2 5 19 20 8 14 18 2 10 10

Sample Output 2 Copy

Copy

7

题目类型:bfs

解题目标:求最后有多少个朋友知道了秘密

解题思路:1)队列,把x压进去;

                  2)不用开二维的vector, 一个朋友只能告诉一个朋友

                   3)压之前,看一下这个朋友是不是已经知道秘密了

AC代码:

#include <bits/stdc++.h>
#define rep(x ,a, b) for(int x =a; x<=b; x++)
#define inf 0x3f3f3f3f
using namespace std;
const int N= 1e5+10;
bool vis[N];
vector<int> f[N];

int main()
{
    int n, x;
    scanf("%d%d", &n, &x);
    rep(i, 1, n)
    {
        int temp;
        scanf("%d", &temp);
        f[i].push_back(temp);
    }
    queue<int> que;
   // cout<<x<<endl;
    que.push(x);
    int ans = 1;
    vis[x] = true;
    while(!que.empty())
    {
        int temp = que.front();
        que.pop();
       // cout<<f[temp]<<"  "<<que.size()<<endl;
        if(!vis[f[temp][0]])
        {
            vis[f[temp][0]] = true;
            ans++;
            que.push(f[temp][0]);
        }
    }
    cout<<ans;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_54674275/article/details/121447528