Smallest Common Region in C++

C++Server Side ProgrammingProgramming

Suppose we have some lists of regions where the first region of each list includes all other regions in that list. basically, if a region X contains another region Y then, X is larger than Y. Also by definition a region X contains itself. So if we have two regions r1 and r2, we have to find the smallest region that contains both of them. So if we have r1, r2 and r3 such that r1 includes r3, it is guaranteed there is no r2 such that r2 includes r3. So if the input is like [["Earth","North America","South America"], ["North America","United States","Canada"], ["United States","New York","Boston"],["Canada","Ontario","Quebec"],["South America","Brazil"]], and r1 = ‘Quebec’ and r2 = ‘New York’, then the output will be ‘North America’

To solve this, we will follow these steps −

  • create a map called parent
  • for i in range 0 to size of r
    • for j in range 1 to size of r[i]
      • parent[r[i, j]] := r[i, 0]
  • create one set called chain, and insert x into chain
  • while x is in the parent,
    • x := parent[x]
    • insert x into chain
  • while y is present in the chain
    • y := parent[y]
  • return y

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   string findSmallestRegion(vector<vector<string>>& r, string x, string y) {
      map < string, string> parent;
      for(int i = 0; i < r.size(); i++){
         for(int j = 1; j < r[i].size(); j++){
            parent[r[i][j]] = r[i][0];
         }
      }
      set <string> chain;
      chain.insert(x);
      while(parent.find(x)!=parent.end()){
         x = parent[x];
         chain.insert(x);
      }
      while(chain.find(y)==chain.end()){
         y = parent[y];
      }
      return y;
   }
};
main(){
   vector<vector<string>> v = {
      {"Earth","North America","South America"},
      {"North America","United States","Canada"},
      {"United States","New York","Boston"},  
      {"Canada","Ontario","Quebec"},{"South America","Brazil"}
   };
   Solution ob;
   cout << (ob.findSmallestRegion(v, "Quebec", "New York"));
}

Input

[["Earth","North America","South America"],["North America","United States","Canada"],
["United States","New York","Boston"],["Canada","Ontario","Quebec"],["South America","Brazil"]]
"Quebec"
"New York"

Output

North America
raja
Published on 02-May-2020 11:57:29
Advertisements