मान लीजिए कि हमारे पास एन तत्वों के साथ एक सरणी ए है। विचार करें कि एन बिल्लियाँ हैं और उन्हें 1 से एन तक गिना जाता है। प्रत्येक बिल्ली ने एक टोपी पहन रखी है और बिल्ली कहती है, "मेरे अलावा बिल्लियों के स्वामित्व वाले एन -1 टोपियों में बिल्कुल ए [i] विभिन्न रंगों की संख्या है"। हमें यह जांचना होगा कि क्या टोपियों के रंगों का एक क्रम मौजूद है जो बिल्लियों की टिप्पणियों के अनुरूप है।
इसलिए, यदि इनपुट A =[1, 2, 2] जैसा है, तो आउटपुट सही होगा, क्योंकि यदि बिल्ली 1, 2 और 3 क्रमशः लाल, नीले और नीले रंग की टोपी पहनती है, तो यह संगत है बिल्लियों की टिप्पणी।
इसे हल करने के लिए, हम इन चरणों का पालन करेंगे -
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 उदाहरण
आइए बेहतर समझ पाने के लिए निम्नलिखित कार्यान्वयन देखें -
#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;
} इनपुट
{ 1, 2, 2 } आउटपुट
1