Official

B - 欠けたアンケートとチーム分け / Missing Survey and Team Division Editorial by kyopro_friends


重要なのは R, W, ? の人数のみであり、誰が何を希望しているかは関係ありません。

よって、 ? のうち何人を赤チームに割り当てるかを実際に \(O(N)\) 通り調べることで \(O(N)\) で答えを求めることができます。

実装例 (C++)

#include<bits/stdc++.h>
using namespace std;

int main(){
  int n;
  cin >> n;
  int r = 0, w = 0, q = 0;
  for(int i=0; i<n; i++){
    char c;
    cin >> c;
    if(c == 'R'){
      r++;
    }else if(c == 'W'){
      w++;
    }else{
      q++;
    }
  }

  int ans = 1e9;
  for(int qw = 0; qw<=q; qw++){
    int ww = w + qw;
    int rr = r + (q - qw);
    ans = min(ans, abs(ww - rr));
  }
  cout << ans << endl;
}

実装例 (Python)

N = int(input())
R, W, Q = 0, 0, 0
for _ in range(N):
  S = input()
  if S=='R':
    R += 1
  elif S =='W':
    W += 1
  else:
    Q += 1

ans = 10**9
for qw in range(Q+1):
  w = W + qw
  r = R + (Q - qw)
  ans = min(ans, abs(w - r))
print(ans)

posted:
last update: