cppAcademy
FROM LEARNING TO COMPETING

Proficient.
Put your skills to the test.

Bulgarian Informatics Group B · 2009–2026

217 independently explained problems: 54 Municipal, 54 Regional and 109 National. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group B also includes challenging national-level problems. National-round tasks shared by Groups A and B are included. Years follow Arena’s competition-season labels. Source clarifications and special grader requirements are noted on affected tasks.
GROUP B2022 · EasySubarray counting

Even Products

National Olympiad — Municipal round (2022 season)

Submission name: even.cpp

Problem summary

Count nonempty contiguous subarrays whose product is even.

Input

n, followed by n positive integers.

Output

The number of qualifying subarrays.

Constraints

0 < n < 10000; 0 < a[i] < 1000.

Worked example

An independently prepared example for this explanation.

Input

4
5 3 2 5

Output

6

Solution analysis

  1. A product is even exactly when at least one of its factors is even. Instead of multiplying anything, remember the most recent even element’s one-based position, initially zero.
  2. At right endpoint r, all starting positions from 1 through lastEven include that most recent even element. Every later starting position contains only odd elements. Add lastEven to the result.
  3. In 5,3,2,5, the first two endpoints contribute zero. At the third element, lastEven becomes 3, and endpoints three and four each contribute three, giving six.

Why it works

For any endpoint, a subarray product is even if and only if its start is at most the latest even position. Thus exactly lastEven valid subarrays end there. Summing over endpoints counts every valid subarray exactly once.

Complexity: O(n) time and O(1) extra space.

Watch out. Do not compute products: they can overflow despite the small inputs. Odd runs may have length zero, and an all-odd sequence has answer zero.

Commented C++17 solution

An independently written complete program with standard headers.

#include<iostream>
// Algorithm: A product is even exactly when at least one of its factors is even.
using namespace std;
int main(){
    int n;
    cin>>n;
    int lastEven=0;
    long long answer=0;
    for(int position=1;position<=n;++position){
        int value;
        cin>>value;
        if(value%2==0){
            lastEven=position;
        }
        answer+=lastEven;
    }
    cout<<answer<<'\n';
}

Source: Arena Olimpiici ↗