leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

2359.cpp (667B)


      1 class Solution {
      2   public:
      3     int closestMeetingNode(vector<int> &e, int node1, int node2) {
      4         const int n = e.size();
      5         vector<int> d(n, -1);
      6 
      7         for (int i = node1, di = 0; i != -1 && d[i] == -1; i = e[i])
      8             d[i] = di++;
      9 
     10         int res = -1, mini = INT_MAX;
     11         for (int i = node2, di = 0; i != -1 && d[i] != -2; i = e[i], di++) {
     12             int t = max(d[i], di);
     13             if (d[i] != -1 && t <= mini) {
     14                 if (t < mini)
     15                     res = i;
     16                 else
     17                     res = min(res, i);
     18                 mini = t;
     19             }
     20             d[i] = -2;
     21         }
     22 
     23         return res;
     24     }
     25 };