---
id: 298
lang: en
translation_of: index.md
source_sha256: 7c48c62aa985dedae6989aa6c2b84da48d223961b3a9e8e551bdaf15d0f91502
title: "P2168: [NOI2015] Homer's Epic — Solution"
description: "Build a k-ary Huffman tree minimizing the sum of leaf weight times depth; here we just count during Huffman merging without really building the tree."
tags: ["OI","Greedy","Huffman","Huffman Coding","Huffman"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "Problem name 荷马史诗 rendered as “Homer's Epic”."
  - "《算法竞赛进阶指南中》 (sic, 中 “in” placed inside the title brackets) read as “in 《算法竞赛进阶指南》” and rendered as the italicised title Advanced Guide to Algorithm Competitions, as in other posts."
  - "The English headings “Introducing to the Huffman Tree” and “The Solution to This Problem” were already in English in the original and are kept verbatim."
---

## Introducing to the Huffman Tree

In *Advanced Guide to Algorithm Competitions*, Li Yudong describes the Huffman problem like this:

> Construct a k-ary tree containing n child nodes, where the i-th leaf node carries weight $w_j$, and minimize $\sum w_i*l_i$, where $l_i$ denotes the distance from the i-th leaf node to the root node.

For a detailed explanation of the Huffman tree, see: [https://www.jianshu.com/p/95fba425be44](https://www.jianshu.com/p/95fba425be44)

<!--more-->

## The Solution to This Problem

We can directly use the counting feature of Huffman tree generation; that is, when solving the problem we won't actually build the tree, we'll only keep track of the accumulated article length and the longest word. We can show this directly in the code:

```cpp
// P2168.cpp
// tag:Huffman
#include <iostream>
#include <queue>
#include <vector>
#include <cstdio>
#include <cmath>
#define ll long long
using namespace std;
const int maxn = 100200;
ll n, k, weights[maxn];
struct node
{
    ll val, mergeTimes;
    bool operator<(const node &nd) const
    {
        return val > nd.val || (val == nd.val) && (mergeTimes > nd.mergeTimes);
    }
};
priority_queue<node> seq;
int main()
{
    scanf("%lld%lld", &n, &k);
    for (int i = 1; i <= n; i++)
        scanf("%lld", &weights[i]), seq.push(node{weights[i], 0});
    ll numOfZero = (k - 1) - (n - 1) % (k - 1);
    numOfZero %= (k - 1);
    for (int i = 0; i < numOfZero; i++)
        seq.push(node{0, 0});
    ll ans = 0, maxans = 0, L = 1;
    for (L = 1; seq.size() != 1; L++)
    {
        int siz = seq.size();
        ll curt = 0, max_val = 0;
        for (int i = 0; i < k; i++)
            curt += seq.top().val, max_val = max(max_val, seq.top().mergeTimes + 1), seq.pop();
        ans += curt, seq.push(node{curt, max_val}), maxans = max(maxans, max_val);
    }
    printf("%lld\n%lld", ans, maxans);
    return 0;
}
```
