C++程式檢查貓戴彩色帽子是否正確
假設我們有一個包含N個元素的陣列A。考慮有N只貓,它們從1到N編號。每隻貓都戴著一頂帽子,第i只貓說“除了我之外,其他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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP