Advertisement
Guest User

Untitled

a guest
Nov 18th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. typedef long long ll;
  9.  
  10. struct Node {
  11. ll value;
  12.  
  13. int left;
  14. int right;
  15.  
  16. Node() { }
  17.  
  18. void set(ll value, int left, int right) {
  19. Node::value = value;
  20. Node::left = !left ? 0 : left - 1;
  21. Node::right = !right ? 0 : right - 1;
  22. }
  23. };
  24.  
  25.  
  26. bool check(vector<Node>& table, size_t i) {
  27. auto cur = &table[i];
  28.  
  29. //leaf -> ok
  30. if (!cur->left)
  31. if (!cur->right)
  32. return true;
  33.  
  34. // *left, 0
  35. // compare values, then check left son
  36. if (!cur->right)
  37. if (cur->left)
  38. return table[cur->left].value >= cur->value ? false : check(table, cur->left);
  39.  
  40. // 0, *right
  41. // compare values, then check right son
  42. if (!cur->left)
  43. if (cur->right)
  44. return table[cur->right].value <= cur->value ? false : check(table, cur->right);
  45.  
  46. // *left, *right
  47. // compare values, then check both
  48. if (table[cur->left].value >= cur->value)
  49. return false;
  50. if (table[cur->right].value <= cur->value)
  51. return false;
  52. if (!check(table, cur->left))
  53. return false;
  54. if (!check(table, cur->right))
  55. return false;
  56.  
  57. // if all pass -> allright
  58. return true;
  59. }
  60.  
  61. int main()
  62. {
  63. ifstream ist("check.in");
  64. ofstream ost("check.out");
  65.  
  66. size_t n;
  67. ist >> n;
  68.  
  69. vector<Node>* table = new vector<Node>(n);
  70.  
  71. for (size_t i = 0; i < n; i++) {
  72. ll value;
  73. int left, right;
  74. ist >> value >> left >> right;
  75.  
  76. table->at(i).set(value, left, right);
  77. }
  78.  
  79. ost << (n == 0 ? "YES" : (check(*table, 0) ? "YES" : "NO"));
  80.  
  81. return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement