Please sign in first.
Official
A - Candy Button Editorial
by
解説
A - Candy Button Editorial
by
yuto1115
解説
AtCoder をはじめたばかりで何をしたらよいか分からない方は、まずは practice contest の問題A「Welcome to AtCoder」を解いてみてください。基本的な入出力の方法が載っています。
また、プログラミングコンテストの問題に慣れていない方は、AtCoder Beginners Selection の問題をいくつか解いてみることをおすすめします。
今までにもらった飴の数、および最後に飴をもらった時刻を管理しながら、\(i=1,2,\dots,N\) の順に、\(i\) 回目にボタンを押した際に飴をもらえるかどうかを判定すればよいです。
具体的には、以下のようなアルゴリズムを実装すればよいです。
- 今までにもらった飴の数を表す変数 \(\mathrm{ans}\)、および最後に飴をもらった時刻を表す変数 \(\mathrm{pre}\) を用意し、それぞれ \(1, T_1\) で初期化する。
- \(i=2,3,\dots,N\) の順に以下を行う。
- \(T_i-\mathrm{pre}\geq C\) ならば、\(\mathrm{ans}\) に \(1\) を足し、\(\mathrm{pre}\) を \(T_i\) で更新する。
これをプログラムにするためには、繰り返し(for 文など)および 条件分岐(if 文など)とよばれる処理を実装する必要があります。具体的な実装方法については、下記の実装例 (C++, Python) を参考にしてください。
実装例 (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;
}
実装例 (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: