公式
B - 不満を感じる回数 / Number of Times Feeling Dissatisfied 解説
by
B - 不満を感じる回数 / Number of Times Feeling Dissatisfied 解説
by
kyopro_friends
高橋君がシールをもらうたびに、条件が満たされているか \(N\) 人全員をチェックしていると、計算量が \(\Theta(NM)\) となるテストケースが存在するため、実行時間制限に間に合わせることは困難です。
「高橋君以外の生徒の中に高橋君よりも厳密に多い枚数のシールを持っている生徒がいる」かどうかを判定するには、「生徒が持っているシールの枚数の最大値」がわかれば十分です。各生徒の持っているシールの枚数を管理しながら追加でこの値を管理することは定数時間でできるため、全体で \(O(N+M)\) でこの問題を解くことができます。
実装例 (C++)
#include<bits/stdc++.h>
using namespace std;
int main(){
int n, m;
cin >> n >> m;
vector<int> cnt(n+1); // cnt[i] = 生徒 i が持っているシールの枚数
int M = 0; // M = max(cnt)
int ans = 0;
for(int i=0; i<m; i++){
int p;
cin >> p;
cnt[p]++;
M = max(M, cnt[p]);
if(p == 2 && M > cnt[2]){
ans++;
}
}
cout << ans << endl;
}
実装例 (Python)
N, M = map(int, input().split())
P = list(map(int, input().split()))
cnt = [0] * (N+1) # cnt[i] = 生徒 i が持っているシールの枚数
m = 0 # m = max(cnt)
ans = 0
for p in P:
cnt[p] += 1
m = max(m, cnt[p])
if p == 2 and m > cnt[2]:
ans += 1
print(ans)
投稿日時:
最終更新:
