1020B - Badge - CodeForces Solution


brute force dfs and similar graphs *1000

Please click on ads to support us..

Python Code:

num = int(input())
students = [int(x) for x in input().split()]
res = []

for i in range(num):
    curr = i + 1
    temp = set()
    while curr not in temp:
        temp.add(curr)
        curr = students[curr - 1]
    res.append(curr)

print(*res)
 		  						 	 				 		 						 		

C++ Code:

/** Read statement carefully **/

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

#define     debug(x)            cout<< #x << " = " << x <<endl;
#define     ll                  long long
#define     yes                 cout<< "Yes" << "\n"
#define     no                  cout<< "No"  << "\n"
#define     eps                 1e-7
#define     pb                  push_back
#define     F                   first
#define     S                   second
#define     endl                "\n"

const int sz  = 2e5 + 5;
const int N = 1e5 + 5;
const int mod = 1e9 + 7;
const ll  Inf = 1e18;
ll dr[] = {-1, +1, 0,   0};
ll dc[] = { 0,  0, +1, -1};

ll n;
ll ara[1005];
map< ll, ll > vis;

ll get(ll u) {
    if(ara[u] == u or vis[u]) {
        return u;
    }
    vis[u] = 1;
    return u = get( ara[u] );

}

void solve() {

    cin>> n;
    for(ll i = 0; i < n; i ++) cin>> ara[i + 1];
    for(ll i = 1; i <= n; i ++) {
        vis.clear();
        cout<< get(i) << ' ';
    }
    cout<< endl;

}


int32_t main()
{

    ios::sync_with_stdio(false);cin.tie(0);
    ll T; T = 1;
    //cin >> T;
    while(T --) {
        solve();

    }


    return 0;

}


Comments

Submit
0 Comments
More Questions

791A - Bear and Big Brother
1452A - Robot Program
344A - Magnets
96A - Football
702B - Powers of Two
1036A - Function Height
443A - Anton and Letters
1478B - Nezzar and Lucky Number
228A - Is your horseshoe on the other hoof
122A - Lucky Division
1611C - Polycarp Recovers the Permutation
432A - Choosing Teams
758A - Holiday Of Equality
1650C - Weight of the System of Nested Segments
1097A - Gennady and a Card Game
248A - Cupboards
1641A - Great Sequence
1537A - Arithmetic Array
1370A - Maximum GCD
149A - Business trip
34A - Reconnaissance 2
59A - Word
462B - Appleman and Card Game
1560C - Infinity Table
1605C - Dominant Character
1399A - Remove Smallest
208A - Dubstep
1581A - CQXYM Count Permutations
337A - Puzzles
495A - Digital Counter