cppAcademy
FROM LEARNING TO COMPETING

Intermediate.
Put your skills to the test.

Bulgarian Informatics Group D · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group D also includes challenging national-level problems. The six 2017 National tasks shared by Groups C and D use their existing permanent URLs. Years follow Arena’s competition-season labels. Source clarifications and special grader requirements are noted on affected tasks.
GROUP D2021 · EasyPrefix sums

Recovering a Mountain Profile

National Olympiad — Municipal round (2021 season)

Submission name: relef.cpp

Problem summary

Recover heights from adjacent comparisons, knowing differences are±1 and the minimum is zero.

Input

N and N−1 signs < or >.

Output

All N heights.

Constraints

1≤N≤100000.

Worked example

Input and output for the worked example discussed below.

Input

15
<<><<>>>><<><<

Output

1 2 3 2 3 4 3 2 1 0 1 2 1 2 3

Solution analysis

  1. Start at temporary height zero. Each < increases the next height by one and each > decreases it by one. These are prefix sums of the prescribed changes.
  2. Track the smallest temporary value, then subtract it from every height. Vertical translation preserves all differences and makes the minimum exactly zero.
  3. The sample walk reaches temporary minimum−1. Adding one to every height gives the displayed profile. With N=1 there are no signs and the answer is zero.

Why it works

The signs determine every consecutive difference, so all compatible profiles differ by a constant. Subtracting the minimum is the unique shift making the minimum zero.

Complexity: O(N) time and O(N) space.

Watch out. Interpret < as increasing height; handle the empty sign sequence at N=1.

Commented C++17 solution

An independently written complete program with standard headers.

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
// The signs determine every consecutive difference, so all compatible profiles differ by a constant.
int main(){
    int n;
    cin>>n;
    vector<int>a(n,0);
    int lowest=0;
    for(int i=1;i<n;i++){
        char sign;
        cin>>sign;
        a[i]=a[i-1]+(sign=='<'?1:-1);
        lowest=min(lowest,a[i]);
    }
    for(int i=0;i<n;i++){
        if(i){
            cout<<' ';
        }
        cout<<a[i]-lowest;
    }
    cout<<'\n';
}

Source: Arena Olimpiici ↗