- Related Questions & Answers
- Count number of trees in a forest in C++
- Convert a tree to forest of even nodes in C++
- Delete Nodes And Return Forest in Python
- Program to Connect a Forest in Python
- Maximum edge removal from tree to make even forest in C++
- Why is Jadav Payeng alias Molai known as Forest Man?
- What are the highlights of India's State Forest Report 2017?
- strcoll() in C/C++
- fseek() in C/C++
- strcpy() in C/C++
- strcmp() in C/C++
- isless() in C/C++
- islessgreater() in C/C++
- Pointers in C/C++
- isgreater() in C/C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

#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)); }

[1,1,2]

5

Advertisements