---
id: 1197
lang: en
translation_of: index.md
source_sha256: 1d570cc74e6f14959cc923d99d104677bdcf39e724c7e08ef5333fb19d3530a8
title: "P2564: [SCOI2009] Birthday Gift — Solution"
description: "A fake monotonic queue. Record each category's indices, put each category's smallest into a multiset, and update the answer with max minus min."
tags: ["OI","Godlike","Balanced BST","STL"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "Problem name 生日礼物 rendered as “Birthday Gift”."
---

## Approach

A fake monotonic queue, heh.

Consider recording the indices of each category's elements, then first put the smallest-numbered element of each category into a multiset, and then update the answer: each time, take out the maximum and the minimum and update with their difference, then update the minimum's index and toss it back into the multiset. If all the categories in the multiset have been fully enumerated, just break out of the loop and output.

<!--more-->

## Code

```cpp
// P2564.cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;
struct node
{
    ll typ, val, dep;
    bool operator<(const node &nd) const { return val < nd.val; }
};
int n, k;
vector<int> typs[100];
multiset<node> st;

int main()
{
    scanf("%d%d", &n, &k);
    for (int i = 1; i <= k; i++)
    {
        int ti;
        scanf("%d", &ti);
        while (ti--)
        {
            int num;
            scanf("%d", &num), typs[i].push_back(num);
        }
        st.insert(node{i, typs[i][0], 0});
    }
    ll ans = 0x3f3f3f3f3f3f3f3f;
    int full = 0;
    while (full < k)
    {
        node small = *st.begin(), biggest = *(--st.end());
        ans = min(ans, biggest.val - small.val);
        st.erase(st.begin());
        if (small.dep + 1 < typs[small.typ].size())
            small.val = typs[small.typ][small.dep + 1], small.dep++;
        else
            full++;
        st.insert(small);
    }
    node small = *st.begin(), biggest = *(--st.end());
    ans = min(ans, biggest.val - small.val);
    printf("%lld", ans);
    return 0;
}
```
