สมมติว่าเรามีอาร์เรย์ A ที่มีองค์ประกอบ N พิจารณาว่ามีแมว N ตัวและพวกมันมีหมายเลขตั้งแต่ 1 ถึง N แมวแต่ละตัวสวมหมวกและแมวบอกว่า "หมวก N-1 ที่มีแมวเป็นเจ้าของมีจำนวนสีต่างกัน A[i] ยกเว้นฉัน" เราต้องตรวจสอบว่ามีลำดับสีของหมวกที่สอดคล้องกับคำพูดของแมวหรือไม่
ดังนั้นหากอินพุตเป็น A =[1, 2, 2] เอาต์พุตจะเป็น True เพราะหากแมว 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