755C - PolandBall and Forest - CodeForces Solution


dfs and similar dsu graphs interactive trees *1300

Please click on ads to support us..

Python Code:

n, P = int(input()), list(map(int, input().split()))
print(sum(P[P[i]-1] == i+1 and P[i] < i+2 for i in range(n)))

C++ Code:

#include<bits/stdc++.h>
using namespace std;

#define endl "\n" ;
#define sort(v) sort(v.begin() , v.end());
#define reverse(v) reverse(v.begin() , v.end());
typedef pair<long long, long long > ii;
typedef vector<long long > vl;
typedef vector<int>vi ;
typedef vector<ii> vii;
typedef long long ll;
typedef  long double ld;

const int  N = 10000 + 5;
int  oo = 100000;
ll const MOD = 1e9 + 7;


int dx[] = { 0, 1, -1,0 };
int dy[] = { 1,0 , 0,-1 };

vi arr[N];
int visited [N];

void dfs(int node ){
    visited[node]=1;
    for (auto child : arr[node]){
        if(!visited[child])dfs(child);
    }
}
int main() {

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n ; cin >> n  ;

    for (int i = 1 ; i <= n ; i ++ ){
        int x ; cin >> x ;
        arr[x].push_back(i);
        arr[i].push_back(x);
    }

    int c = 0 ;

    for (int i = 1 ; i <= n ; i ++ ){
        if(!visited[i]){
            c++;
            dfs(i);
        }
    }

    cout << c ;

    return 0;


}


Comments

Submit
0 Comments
More Questions

1277A - Happy Birthday Polycarp
577A - Multiplication Table
817C - Really Big Numbers
1355A - Sequence with Digits
977B - Two-gram
993A - Two Squares
1659D - Reverse Sort Sum
1659A - Red Versus Blue
1659B - Bit Flipping
1480B - The Great Hero
1519B - The Cake Is a Lie
1659C - Line Empire
515A - Drazil and Date
1084B - Kvass and the Fair Nut
1101A - Minimum Integer
985D - Sand Fortress
1279A - New Year Garland
1279B - Verse For Santa
202A - LLPS
978A - Remove Duplicates
1304A - Two Rabbits
225A - Dice Tower
1660D - Maximum Product Strikes Back
1513A - Array and Peaks
1251B - Binary Palindromes
768B - Code For 1
363B - Fence
991B - Getting an A
246A - Buggy Sorting
884A - Book Reading