Solving a real problem
The problem
Section titled “The 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.
The algo solution
Section titled “The algo solution”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:
./algo compile solution.alg -o solution.cppg++ -std=c++17 -O2 solution.cpp -o solutionInput:
51 3 5 7 933610Output:
135What was generated
Section titled “What was generated”#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.
The key constructs
Section titled “The key constructs”input: block
Section titled “input: block”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:
Section titled “repeat q:”repeat q: input: x: int println lower(a, x)Use repeat when you want a counted loop without an index variable.
sort(a)
Section titled “sort(a)”sort(a)Sorts the array in place in ascending order.
lower(a, x)
Section titled “lower(a, x)”lower(a, x) # first index where a[idx] >= xupper(a, x) # first index where a[idx] > xThese are direct wrappers around standard binary-search operations on sorted arrays.
Why this example matters
Section titled “Why this example matters”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