Grade 9 · Number sequences read one at a timeCitește în română

Pairs of consecutive terms with a property

Original: Perechi de termeni consecutivi cu o proprietate

O(n)C++1737 lines1 example

The idea

We count the pairs of adjacent terms that have the same parity. A sequence of n terms has n - 1 consecutive pairs; for every new term x, the pair is (ant, x). Two terms have the same parity exactly when their sum is even.

Original description (Romanian)

Numărăm perechile de termeni aflați unul după altul care au aceeași paritate. Un șir de n termeni are n - 1 perechi consecutive; pentru fiecare termen nou x, perechea este (ant, x). Doi termeni au aceeași paritate exact când suma lor este pară.

Complexity
O(n)
Grade
Grade 9 (Clasa a IX-a)

Examples

Example 1

Input

6
2 4 7 9 10 3

Expected output

2

The code

Comments are in Romanian, as in the original collection. Edit freely: you can reset at any time.

perechi-consecutive.cpp
/*
 * Titlu: Perechi de termeni consecutivi cu o proprietate
 * Clasa: 9
 * Capitol: Șiruri de numere citite pe rând
 * Descriere: Numărăm perechile de termeni aflați unul după altul care au
 *            aceeași paritate. Un șir de n termeni are n - 1 perechi
 *            consecutive; pentru fiecare termen nou x, perechea este (ant, x).
 *            Doi termeni au aceeași paritate exact când suma lor este pară.
 * Complexitate: O(n)
 *
 * Exemplu
 * Intrare:
 * 6
 * 2 4 7 9 10 3
 * Ieșire: 2
 */
#include <iostream>
using namespace std;

int main()
{
    int n, perechi = 0;
    long long ant, x;
    cin >> n >> ant;
    for (int i = 2; i <= n; i++)
    {
        cin >> x;
        if ((ant + x) % 2 == 0)
        {
            perechi++;
        }
        ant = x;
    }
    cout << perechi << '\n';
    return 0;
}

Runs on a real g++ (C++17, -O2) through Compiler Explorer. Keep runs short; there's a time limit.