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

示例

让我们看看下面的实现以获得更好的理解:

Open Compiler
#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 }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

1

更新于:2022年2月25日

146 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告