797D - Broken BST - CodeForces Solution


data structures dfs and similar *2100

Please click on ads to support us..

C++ Code:

// https://codeforces.com/contest/797/problem/D
#include <bits/stdc++.h>
using namespace std;

int vals[100005];
pair<int, int> children[100005];
map<int, int> occ;
map<int, bool> works;

void dfs(int index, int left, int right) {
  if (left < vals[index] && vals[index] < right) {
    works[vals[index]] = true;
  }
  if (children[index].first != -2) {
    dfs(children[index].first, left, min(right, vals[index]));
  }
  if (children[index].second != -2) {
    dfs(children[index].second, max(left, vals[index]), right);
  }
}

int main() {
  cin.tie(NULL)->sync_with_stdio(false);
  int n;
  cin >> n;

  for (int i = 0; i < n; i++) {
    cin >> vals[i] >> children[i].first >> children[i].second; 
    occ[vals[i]]++;
    works[vals[i]] = false;
    children[i].first--;
    children[i].second--;
  }

  // find root
  int root = 0;
  bool root_poss[n] = {};
  for (int i = 0; i < n; i++) {
    if (children[i].first != -2) root_poss[children[i].first] = true;
    if (children[i].second != -2) root_poss[children[i].second] = true;
  }
  for (int i = 0; i < n; i++) if (root_poss[i] == false) root = i;

  // dfs, keep track of range of vals
  dfs(root, -2, 1000000001);

  int out = 0;
  for (auto thing : works) {
    if (!thing.second) out += occ[thing.first];
  }
  cout << out;
}


Comments

Submit
0 Comments
More Questions

1733A - Consecutive Sum
1733B - Rule of League
1733C - Parity Shuffle Sorting
1264A - Beautiful Regional Contest
1695A - Subrectangle Guess
467B - Fedor and New Game
252C - Points on Line
735C - Tennis Championship
992A - Nastya and an Array
554A - Kyoya and Photobooks
79B - Colorful Field
265B - Roadside Trees (Simplified Edition)
1362C - Johnny and Another Rating Drop
1214C - Bad Sequence
1091B - New Year and the Treasure Geolocation
244A - Dividing Orange
1061C - Multiplicity
1312A - Two Regular Polygons
801A - Vicious Keyboard
510B - Fox And Two Dots
616D - Longest k-Good Segment
1604A - Era
555B - Case of Fugitive
551A - GukiZ and Contest
1399F - Yet Another Segments Subset
1371C - A Cookie for You
430B - Balls Game
1263A - Sweet Problem
1332B - Composite Coloring
254A - Cards with Numbers