C++ program to count number of cities we can visit from each city with given operations

C++Server Side ProgrammingProgramming

Suppose we have a list of N coordinate points P in the form (xi, yi). The x and y values are permutation of first N natural numbers. For each k in range 1 to N. We are at city k. We can apply the operations arbitrarily many times. The operation: We move to another city that has a smaller x-coordinate and a smaller y-coordinate or larger x or larger y coordinate than the city we are currently in. We have to find the number of cities we can reach from city k.

So, if the input is like P = [[1, 4], [2, 3], [3, 1], [4, 2]], then the output will be [1, 1, 2, 2]

Steps

To solve this, we will follow these steps −

n := size of P
Define one 2D array lst
for initialize i := 0, when i < n, update (increase i by 1), do:
   v := { P[i, 0], P[i, 1], i }
   insert v at the end of lst
sort the array lst
y_min := 1e9
Define one set se
Define an array ans of size n and fill with 0
for initialize i := 0, when i < n, update (increase i by 1), do:
   y_min := minimum of y_min and lst[i, 1]
   insert lst[i, 2] into se
   if y_min + i is same as n, then:
      for each element j in se
         ans[j] := size of se
      clear the set se
   if i is same as n - 1, then:
      for each element j in se
         ans[j] := size of se
for initialize i := 0, when i < n, update (increase i by 1), do:
   display ans[i]

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

void solve(vector<vector<int>> P){
   int n = P.size();
   vector<vector<int>> lst;
   for (int i = 0; i < n; i++){
      vector<int> v = { P[i][0], P[i][1], i };
      lst.push_back(v);
   }
   sort(lst.begin(), lst.end());
   int y_min = 1e9;
   set<int> se;
   vector<int> ans(n, 0);
   for (int i = 0; i < n; i++){
      y_min = min(y_min, lst[i][1]);
      se.insert(lst[i][2]);
      if (y_min + i == n){
         for (auto j : se)
            ans[j] = se.size();
         se.clear();
      }
      if (i == n - 1){
         for (auto j : se)
            ans[j] = se.size();
      }
   }
   for (int i = 0; i < n; i++){
      cout << ans[i] << ", ";
   }
}
int main(){
   vector<vector<int>> P = { { 1, 4 }, { 2, 3 }, { 3, 1 }, { 4, 2 } };
   solve(P);
}

Input

{ { 1, 4 }, { 2, 3 }, { 3, 1 }, { 4, 2 } }

Output

1, 1, 2, 2,
raja
Updated on 03-Mar-2022 07:50:08

Advertisements