Advertisement
snowywhitee

Untitled

Dec 2nd, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <fstream>
  4. using namespace std;
  5.  
  6. struct node {
  7.     int key;
  8.     vector < int > kids;
  9. };
  10.  
  11. vector < node > arr;
  12.  
  13. bool dfs(vector < node > &arr, int key, int pos)
  14. {
  15.     int parent = key;
  16.     int leftchild, rightchild, leftpos, rightpos;
  17.     leftchild = rightchild = leftpos = rightpos = -1;
  18.     if (arr[pos].kids[0] != -1)
  19.     {
  20.         leftchild = arr[arr[pos].kids[0]].key;
  21.         leftpos = arr[pos].kids[0];
  22.     }
  23.    
  24.     if (arr[pos].kids[1] != -1)
  25.     {
  26.         rightchild = arr[arr[pos].kids[1]].key;
  27.         rightpos = arr[pos].kids[1];
  28.     }
  29.    
  30.     if (leftpos != -1 && rightpos != -1)
  31.     {
  32.         if (leftchild > parent || rightchild < parent)
  33.         {
  34.             return false;
  35.         } else {
  36.             return (dfs(arr, leftchild, leftpos) && dfs(arr, rightchild, rightpos));
  37.         }
  38.     } else if (leftpos == -1 && rightpos == -1)
  39.     {
  40.         return true;
  41.     } else if (leftpos != -1 && rightpos == -1)
  42.     {
  43.         if (leftchild > parent)
  44.         {
  45.             return false;
  46.         } else {
  47.             return dfs(arr, leftchild, leftpos);
  48.         }
  49.     } else if (leftpos == -1 && rightpos != -1)
  50.     {
  51.         if (rightchild < parent)
  52.         {
  53.             return false;
  54.         } else {
  55.             return dfs(arr, rightchild, rightpos);
  56.         }
  57.     }
  58. }
  59.  
  60. int main()
  61. {
  62.     ifstream fin("1.txt");
  63.     ofstream fout("2.txt");
  64.    
  65.     int n;
  66.     fin >> n;
  67.     arr.resize(n);
  68.     int key, num1, num2;
  69.     if (n == 0)
  70.     {
  71.         cout << "YES";
  72.     } else {
  73.         for (int i = 0; i < n; i++)
  74.         {
  75.             fin >> key;
  76.             fin >> num1 >> num2;
  77.             arr[i].key = key;
  78.             arr[i].kids.push_back(num1 - 1);
  79.             arr[i].kids.push_back(num2 - 1);
  80.         }
  81.        
  82.         if (dfs(arr, arr[0].key, 0))
  83.         {
  84.             cout << "YES";
  85.         } else {
  86.             cout << "NO";
  87.         }
  88.     }
  89.    
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement