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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值