公式

B - Odd Position Sum 解説 by en_translator


For beginners

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]))

投稿日時:
最終更新: