Official

B - Candy Button Editorial by en_translator


If you are new to learning programming and do not know where to start, please try Problem A “Welcome to AtCoder” from practice contest. There you can find a sample code for each language.
Also, if you are not familiar with problems in programming contests, we recommend you to try some problems in “AtCoder Beginners Selection” (https://atcoder.jp/contests/abs).


Manage the number of candies he has received so far, and the last time he received a candy, while scanning \(i=1,2,\dots,N\) to check if he can receive a candy when pressing the button for the \(i\)-th time.

Specifically, implement the following algorithm.

  1. Prepare a variable \(\mathrm{ans}\) that represents the number of candies received so far, and \(\mathrm{pre}\) that represents the last time he received a candy, initialized with \(1\) and \(T_1\), respectively.
  2. For \(i=2,3,\dots,N\), do the following:
    • if \(T_i-\mathrm{pre}\geq C\), add \(1\) to \(\mathrm{ans}\), and set \(\mathrm{pre}\) to \(T_i\).

To make it a code, you need to implement process called repetition (like for statement) and conditional branch (like if statement). For more details, please refer to the sample code (C++ and Python) below.

Sample code (C++) :

#include <bits/stdc++.h>

using namespace std;

int main() {
    int n, c;
    cin >> n >> c;
    int ans = 1, pre;
    cin >> pre;
    for (int i = 1; i < n; i++) {
        int t;
        cin >> t;
        if (t - pre >= c) {
            ++ans;
            pre = t;
        }
    }
    cout << ans << endl;
}

Sample code (Python) :

n, c = map(int, input().split())
t = list(map(int, input().split()))
ans = 1
pre = t[0]
for i in range(1, n):
    if t[i] - pre >= c:
        ans += 1
        pre = t[i]
        
print(ans)

posted:
last update: