34D - Road Map - CodeForces Solution


dfs and similar graphs *1600

Please click on ads to support us..

Python Code:

n,r1,r2=map(int,input().split())

P=list(map(int,input().split()))

E=[[] for i in range(n+1)]

x=1
for i in range(n-1):
    if x==r1:
        x+=1
    p=P[i]
    E[x].append(p)
    E[p].append(x)

    x+=1


P2=[-1]*(n+1)

Q=[r2]

while Q:
    x=Q.pop()
    for to in E[x]:
        if P2[to]==-1:
            P2[to]=x
            Q.append(to)

ANS=P2[1:r2]+P2[r2+1:n+1]
print(*ANS)

C++ Code:

#include <iostream>
#include <vector>
#include <stack>
#include <string>
#include <utility>
#include <queue>
#include <iomanip>
#include <set>
#include <map>
#include <cmath>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
using namespace std;
#define vi vector<int>
#define ll long long

const int N = 5e4 + 5;
vector<int> v[N];
int ans[N];

void dfs(int n) {
	for (auto& a : v[n]) {
		if (a == ans[n])
			continue;

		ans[a] = n;
		dfs(a);
	}
}


int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	int n, r1, r2;
	cin >> n >> r1 >> r2;
	
	for (int i = 1; i <= n; ++i) {
		if (i == r1)
			continue;

		int x;
		cin >> x;
		v[i].push_back(x);
		v[x].push_back(i);
	}
	
	dfs(r2);
	for (int i = 1; i <= n; ++i) {
		if (i == r2)
			continue;

		cout << ans[i] << ' ';
	}

	return 0;
}
	  	  	  			 	 		  		    	 			


Comments

Submit
0 Comments
More Questions

1335A - Candies and Two Sisters
96B - Lucky Numbers (easy)
1151B - Dima and a Bad XOR
1435B - A New Technique
1633A - Div 7
268A - Games
1062B - Math
1294C - Product of Three Numbers
749A - Bachgold Problem
1486B - Eastern Exhibition
1363A - Odd Selection
131B - Opposites Attract
490C - Hacking Cypher
158B - Taxi
41C - Email address
1373D - Maximum Sum on Even Positions
1574C - Slay the Dragon
621A - Wet Shark and Odd and Even
1395A - Boboniu Likes to Color Balls
1637C - Andrew and Stones
1334B - Middle Class
260C - Balls and Boxes
1554A - Cherry
11B - Jumping Jack
716A - Crazy Computer
644A - Parliament of Berland
1657C - Bracket Sequence Deletion
1657B - XY Sequence
1009A - Game Shopping
1657A - Integer Moves