Rabbits in Forest in C++

C++Server Side ProgrammingProgramming

Suppose In a forest, each rabbit has some color. Now some subset of rabbits (possibly all of them) will tell us how many other rabbits have the same color as them. Those answers are placed in an array. We have to find the minimum number of rabbits that could be in the forest. So if the input is like [1,1,2], then the output will be 5, as the two rabbits that answered "1" that could both be the same color, say white. Now the rabbit than answered "2" can't be white or the answers would be inconsistent. Say the rabbit that answered "2" was black. Then there should be 2 other black rabbits in the forest that didn't answer into the array. So the smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.

To solve this, we will follow these steps −

  • make a map m, and n := size of array ans
  • set ret as 0
  • for i in range 0 to n – 1
    • x := ans[i]
    • if x = 0, then increase ret by 1, and skip the next part of this iteration.
    • if m has x, then increase ret by (x + 1), set m[x] := 0
    • otherwise
      • increase m[x] by 1
      • if m[x] = x, then delete x from m
  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int numRabbits(vector<int>& ans) {
      map <int, int> m;
      int n = ans.size();
      int ret = 0;
      for(int i = 0; i < n; i++){
         int x = ans[i];
         if(x == 0){
            ret++;
            continue;
         }
         if(!m.count(x)){
            ret += (x + 1);
            m[x] = 0;
            }else{
               m[x]++;
           if(m[x] == x){
               m.erase(x);
            }
         }
      }
      return ret;
   }
};
main(){
   vector<int> v = {1,1,2};
   Solution ob;
   cout << (ob.numRabbits(v));
}

Input

[1,1,2]

Output

5
raja
Published on 04-May-2020 14:12:34
Advertisements