CSES - Stick Divisions

Authors: Dong Liu, Benjamin Qi

In this problem, we're asked to find the minimum cost to divide a stick with length xx into nn sticks with given lengths. It helps to work backwards; what if we start with sticks of lengths d1,,dnd_1,\ldots,d_n and merge them into one?

It turns out that this can be solved using Huffman Coding (also see Wikipedia). The algorithm is simple; take the two shortest sticks, merge them into one, and repeat.

If you're wondering why Huffman Coding always produces an optimal solution, see here.

Implementation

C++

In C++, this can be done easily with a priority queue.

#include <iostream>
#include <queue>
using namespace std;
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
int x, n; cin >> x >> n;
priority_queue<int, vector<int>, greater<int> > PQ;
for(int i=0; i<n; i++) {
int a; cin >> a;

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!