D - Japanese Cursed Doll 解説 by en_translator
\((T-1)\) days later, everyone has hair of length \(T\) or greater. Together with \(P\leq N\), the condition is always satisfied then.
Thus, one can find the answer, i.e. the first day on which the conditions are satisfied, by checking if the conditions are satisfied on day \(i\) for each \(i=0,1,,\ldots,(T-1)\) in order.
One can check if the conditions are satisfied with a for
statement and an if
statement. The complexity is \(O(NT)\), which is fast enough for the constraints this time.
Therefore, the problem has been solved.
This problem can also be solved in a total of \(O(N\log N)\) time by recording how many days are required for each person to have hair of length \(T\) or greater, sort the counts of days, and find the \(P\)-th smallest one among them.
Sample code in C++:
#include <bits/stdc++.h>
using namespace std;
int main(void){
int n,t,p;
int l[100];
int cnt;
cin >> n >> t >> p;
for(int i = 0; i < n; i++)cin >> l[i];
for(int i = 0; i < t; i++){
cnt=0;
for(int j = 0; j < n; j++){
if(l[j]+i >= t)cnt++;
}
if(cnt>=p){
cout<< i <<endl;
return 0;
}
}
return 0;
}
Sample code in Python:
n,t,p=map(int, input().split())
l=list(map(int, input().split()))
for i in range(t):
cnt=0
for j in range(n):
if l[j]+i>=t:
cnt+=1
if cnt>=p:
print(i)
break
Sample code in C++ (another solution):
#include <bits/stdc++.h>
using namespace std;
int main(void){
int n,t,p,x;
int l[100];
cin >> n >> t >> p;
for(int i = 0; i < n; i++){
cin >> x;
l[i]=max(0,t-x);
}
sort(l,l+n);
cout << l[p-1] << endl;
return 0;
}
投稿日時:
最終更新: