cppAcademy
FROM LEARNING TO COMPETING

Real problems.
Your next challenge.

Explore the Group C Olympiad archive.
Choose a topic. Find a challenge. Build your solution.

213 tasks across the Municipal, Regional, and National rounds (2009–2026), plus 4 previously featured problems. 146 tasks have independently written English summaries, analyses, and C++17 solutions; the remaining entries link to Arena. Topic tags are from Arena or our reviewed explanations. Difficulty labels are learning estimates, not official ratings.
GROUP C2012 · MediumInterval Costs

Bus Passes

National Olympiad — Municipal round

Submission name: bus.cpp

Problem summary

Stops 1…K lie on one bus line. Ordinary travel costs one unit per adjacent pair. The whole line is partitioned into N consecutive routes whose neighboring endpoints coincide. A pass for a route costs less than its full length and permits travel within that route. Find the minimum cost from stop A to stop B. Routes may be listed in any order.

Input

N A B, then N triples p q s: route endpoints and pass price.

Output

The minimum total fare.

Constraints

1≤N≤100; A<B; K<5000.

Worked example

An independently prepared example for this explanation.

Input

2 3 9
1 5 3
5 10 2

Output

4

Solution analysis

  1. For each route, compute the length t of its overlap with [A,B].
  2. That portion can be paid with t ordinary tickets or the route’s pass, so contribute min(t,s).
  3. Sum independently over routes.

Why it works

Route interiors are disjoint and every traversed edge belongs to exactly one route. A pass for another route cannot cover it; choosing the cheaper of tickets and its own pass in each route is both necessary and achievable.

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

Watch out. A pass can be worthwhile even if only part of its route is travelled. Do not assume sorted input.

Commented C++17 solution

An independently written complete program with standard headers.

// Key idea: Route interiors are disjoint and every traversed edge belongs to exactly one route. A pass
// for another route cannot cover it; choosing the cheaper of tickets and its own pass in each route is
// both necessary and achievable.
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
    int n,a,b;
    cin>>n>>a>>b;
    int ans=0;
    while(n--){
        int p,q,s;
        cin>>p>>q>>s;
        int overlap=max(0,min(b,q)-max(a,p));
        ans+=min(overlap,s);
    }
    cout<<ans<<'\n';
}

Source: Arena Olimpiici ↗