B - Odd Position Sum 解説 by en_translator
For beginners
- 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".
- 「C++入門 AtCoder Programming Guide for beginners (APG4b)」 is a C++ tutorial for competitive programmers. Sadly, this is only in Japanese too.
- 「Python入門 AtCoder Programming Guide for beginners (APG4bPython)」 is a Python tutorial for competitive programmers. Again, this is only in Japanese.
This problem can be solved with for
and if
statements.
First, initialize a variable ans
with 0
, which is used to store the answer. Use a for
statement with an index \(i\) to scan the array \(A\) from the left; if i
corresponds to odd-indexed positions (\(1\)-st, \(3\)-rd, \(5\)-th, \(\ldots\)), add A[i]
to ans
.
Many programming languages adopt 0-based indices, so the odd-indexed elements (\(A_1, A_3, A_5, \dots\)) correspond to i = 0, 2, 4, ...
in the code. Thus, we may perform the addition when i % 2 == 0
.
Sample code (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >> N;
vector<int> A(N);
for (int i = 0; i < N; i++) {
cin >> A[i];
}
int ans = 0;
for (int i = 0; i < N; i++) {
if (i % 2 == 0) {
ans += A[i];
}
}
cout << ans << endl;
}
Sample code(Python)
N = int(input())
A = [int(i) for i in input().split()]
ans = 0
for i in range(N):
if i % 2 == 0:
ans += A[i]
print(ans)
In Python, one can also simplify the code with the slice syntax [::2]
. This means extracting every two elements, starting from the \(0\)-th:
N = int(input())
A = list(map(int, input().split()))
print(sum(A[::2]))
投稿日時:
最終更新: