Snuke the doctor prescribed N kinds of medicine for Takahashi. For the next a i days (including the day of the prescription), he has to take b i pills of the i-th medicine. He does not have to take any other medicine. Let the day of the prescription be day 1. On or after day 1, when is the first day on which he has to take K pills or less? Constraints 1≤N≤3×10 5 0≤K≤10 9 1≤a i ,b i ≤10 9 All input values are integers. Input The input is given from Standard Input in the following format: N K a 1 b 1 ⋮ a N b N Output If Takahashi has to take K pills or less on day X for the first time on or after day 1, print X. Sample Input 1 Copy 4 8 6 3 2 5 1 9 4 2 Sample Output 1 Copy 3c++代码
时间: 2024-01-05 16:02:33 浏览: 75
Sure! Here's the C++ code that calculates the first day on which Takahashi has to take K pills or less:
```cpp
#include <iostream>
#include <vector>
int main() {
int N, K;
std::cin >> N >> K;
std::vector<int> a(N);
std::vector<int> b(N);
for (int i = 0; i < N; i++) {
std::cin >> a[i] >> b[i];
}
long long day = 1;
long long remainingPills = 0;
for (int i = 0; i < N; i++) {
remainingPills += a[i];
if (remainingPills >= K) {
std::cout << day << std::endl;
return 0;
}
day++;
remainingPills -= b[i];
if (remainingPills <= 0) {
remainingPills = 0;
}
}
day += (remainingPills + K - 1) / K;
std::cout << day << std::endl;
return 0;
}
```
In this code, we first take the inputs N and K, representing the number of medicine types and the maximum number of pills Takahashi can take in a day. Then we take the arrays `a` and `b`, where `a[i]` represents the number of days Takahashi has to take `b[i]` pills of the `i-th` medicine.
We iterate through the arrays and keep track of the remaining pills. If at any point the remaining pills are greater than or equal to K, we output the current day and exit the program. Otherwise, we increment the day counter, reduce the remaining pills by `b[i]`, and if the remaining pills become less than or equal to 0, we set it to 0.
Finally, if there are still remaining pills, we calculate the additional days needed by dividing the remaining pills by K (rounded up) and add it to the current day. The result is the first day on which Takahashi has to take K pills or less.
Please note that this code assumes valid inputs and does not include any error handling.
阅读全文