- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to check cats words are right or not with colored hats
Suppose we have an array A with N elements. Consider there are N cats and they are numbered from 1 to N. Each cat is wearing a hat and ith cat says "there are exactly A[i] number of different colors among the N-1 hats owned by the cats except me". We have to check whether there exists a sequence of colors of the hats which is consistent with the remarks of the cats.
So, if the input is like A = [1, 2, 2], then the output will be True, because if cat 1, 2 and 3 wears hats in colors say red, blue and blue hats, respectively, it is consistent with the remarks of the cats.
To solve this, we will follow these steps −
mn := inf, mx = 0, cnt = 0 n := size of A Define an array a of size (n + 1) for initialize i := 1, when i <= n, update (increase i by 1), do: a[i] := A[i - 1] mn := minimum of mn and a[i] mx = maximum of mx and a[i] for initialize i := 1, when i <= n, update (increase i by 1), do: if a[i] is same as mn, then: (increase cnt by 1) if mx is same as mn, then: if mn is same as n - 1 or 2 * mn <= n, then: return true Otherwise return false otherwise when mx is same as mn + 1, then: if mn >= cnt and n - cnt >= 2 * (mx - cnt), then: return true Otherwise return false Otherwise return false
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; bool solve(vector<int> A) { int mn = 99999, mx = 0, cnt = 0; int n = A.size(); vector<int> a(n + 1); for (int i = 1; i <= n; ++i) { a[i] = A[i - 1]; mn = min(mn, a[i]), mx = max(mx, a[i]); } for (int i = 1; i <= n; ++i) if (a[i] == mn) ++cnt; if (mx == mn) { if (mn == n - 1 || 2 * mn <= n) return true; else return false; } else if (mx == mn + 1) { if (mn >= cnt && n - cnt >= 2 * (mx - cnt)) return true; else return false; } else return false; } int main() { vector<int> A = { 1, 2, 2 }; cout << solve(A) << endl; }
Input
{ 1, 2, 2 }
Output
1
Advertisements