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 into sticks with given lengths. It helps to work backwards; what if we start with sticks of lengths 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.

1#include <iostream>
2#include <queue>
3using namespace std;
4
5int main(){
6 ios_base::sync_with_stdio(0); cin.tie(0);
7 int x, n; cin >> x >> n;
8 priority_queue<int, vector<int>, greater<int> > PQ;
9 for(int i=0; i<n; i++) {
10 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!

Give Us Feedback on CSES - Stick Divisions!