B - Grandma's Footsteps 解説 by en_translator
Implementation approach
Since he runs at a constant speed of \(S\) meters per second, we can find the answer by finding how many seconds he runs, and then multiplying it by \(S\).
Simulation solution
Regard that at the moment of starting “he has been running zero seconds,” and initialize the total running duration by \(0\). Perform a simulation by updating the state step-by-state for each second, and you can find how many seconds he runs in total.
For each step, execute the following procedure:
- If his current state is “running,” increment the running duration by \(1\) second.
- Then, increment the time passed since the last event. Then modify the current state as follows:
- If the current state is “he has been running for \(A\) seconds,” change it to “he has been stopping for zero seconds.”
- If the current state is “he has been stopping for \(B\) seconds,” change it to “he has been running for zero seconds.”
More concise solution
Since he repeats the same movement every \((A+B)\) seconds, his \(X\)-second movement can be decomposed into \(\lfloor \frac{X}{A+B} \rfloor\) repetitions and a remainder of \(X \bmod (A+B)\) seconds. (\(\lfloor \frac{X}{A+B} \rfloor\) and \(X \bmod (A+B)\) denotes the quotient and remainder when dividing \(X\) by \((A+B)\), respectively.)
Since each repetition consists of \(A\)-second running and \(B\)-second stopping, he runs for \(A \times \lfloor \frac{X}{A+B} \rfloor\) during the repetition part.
Let \(m\) seconds be the remainder part. During this part, he runs for:
- \(m\) seconds if \(m \leq A\);
- \(A\) seconds if \(m > A\).
By summing up the two values, the total length of the duration where he runs can be found.
Sample code (C++)
The solution of simulating one second by one can be written as follows.
#include <iostream>
using std::cin;
using std::cout;
using std::min;
int main (void) {
int s, a, b, x;
cin >> s >> a >> b >> x;
int len = 0;
int mode = 0, cnt = 0; // mode 0: run, mode 1: stop
for (int i = 0; i < x; i++) {
if (mode == 0) len++;
cnt++;
if (mode == 0 && cnt == a) {
mode = 1;
cnt = 0;
} else if (mode == 1 && cnt == b) {
mode = 0;
cnt = 0;
}
}
int ans = len * s;
cout << ans << "\n";
return 0;
}
The arithmetic solution can be implemented as follows.
#include <iostream>
using std::cin;
using std::cout;
using std::min;
int main (void) {
int s, a, b, x;
cin >> s >> a >> b >> x;
int len = 0;
len += (x / (a+b)) * a; // repeats (a+b) seconds
len += min(x % (a+b), a); // remainder
int ans = len * s;
cout << ans << "\n";
return 0;
}
投稿日時:
最終更新: