1900C - Anji's Binary Tree - CodeForces Solution


dfs and similar dp shortest paths trees

Please click on ads to support us..

C++ Code:

//@author: DroseUnbreakble
#include <bits/stdc++.h>
#define fi first
#define se second
using namespace std;
const int N = 3e5 + 3;

int note[N];
string s;
pair <int, int> a[N];

int trace(int id) {

    if(a[id].fi == 0 && a[id].se == 0) return 0;

    int &ret = note[id];

    if(ret != -1) return ret;
    ret = 1e9;

    if(s[id] == 'U') {
        if(a[id].fi) ret = min(ret, trace(a[id].fi) + 1);
        if(a[id].se) ret = min(ret, trace(a[id].se) + 1);
    }

    if(s[id] == 'L') {
        if(a[id].fi) ret = min(ret, trace(a[id].fi));
        if(a[id].se) ret = min(ret, trace(a[id].se) + 1);
    }

    if(s[id] == 'R') {
        if(a[id].fi) ret = min(ret, trace(a[id].fi) + 1);
        if(a[id].se) ret = min(ret, trace(a[id].se));
    }

    return ret;
}

int32_t main(){
   cin.tie(0)->sync_with_stdio(0);
   if(fopen("sus.inp", "r")){
     freopen("sus.inp", "r", stdin);
     freopen("sus.out", "w", stdout);
   }

   int t;
   cin >> t;
   while(t--) {
      memset(note, -1, sizeof(note));
      int n;
      cin >> n;
      cin >> s; s = " " + s;
      for(int i = 1; i <= n; i++) cin >> a[i].fi >> a[i].se;

      int ans = trace(1);
      cout << ans << '\n';
   }
}


Comments

Submit
0 Comments
More Questions

441C - Valera and Tubes
1328E - Tree Queries
265A - Colorful Stones (Simplified Edition)
296A - Yaroslav and Permutations
967B - Watering System
152A - Marks
1398A - Bad Triangle
137A - Postcards and photos
1674D - A-B-C Sort
334A - Candy Bags
855A - Tom Riddle's Diary
1417A - Copy-paste
1038A - Equality
1061A - Coins
1676E - Eating Queries
1447A - Add Candies
1721D - Maximum AND
363C - Fixing Typos
1401A - Distance and Axis
658A - Bear and Reverse Radewoosh
1721E - Prefix Function Queries
977E - Cyclic Components
1140D - Minimum Triangulation
75C - Modified GCD
1722A - Spell Check
1722B - Colourblindness
1722D - Line
1722C - Word Game
1722G - Even-Odd XOR
552E - Vanya and Brackets