Skip to content

Solving a real problem

Given a sorted array a of n integers and q queries, for each query value x find the number of elements in a that are less than x.

This is a standard contest pattern: sort once, then answer each query with lower bound.

input:
n: int
a: [int][n]
q: int
sort(a)
repeat q:
input:
x: int
println lower(a, x)

lower(a, x) returns the first index where a[idx] >= x. That index is also the count of elements less than x.

Compile it:

Terminal window
./algo compile solution.alg -o solution.cpp
g++ -std=c++17 -O2 solution.cpp -o solution

Input:

5
1 3 5 7 9
3
3
6
10

Output:

1
3
5
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n; cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
int q; cin >> q;
sort(a.begin(), a.end());
while (q--) {
int x; cin >> x;
cout << (int)(lower_bound(a.begin(), a.end(), x) - a.begin()) << "\n";
}
return 0;
}

The important part is not that the output is short. It is that the generated C++ matches the standard solution shape closely enough to inspect and trust.

input:
n: int
a: [int][n]

The declaration shape matches the problem statement directly. The generated C++ still does the usual vector<int> a(n) plus read loop.

repeat q:
input:
x: int
println lower(a, x)

Use repeat when you want a counted loop without an index variable.

sort(a)

Sorts the array in place in ascending order.

lower(a, x) # first index where a[idx] >= x
upper(a, x) # first index where a[idx] > x

These are direct wrappers around standard binary-search operations on sorted arrays.

This is the typical algo tradeoff:

  • source stays close to the problem statement
  • the generated C++ stays close to the standard contest implementation
  • you still use familiar algorithms like sort and lower bound

What algo is optimized for →