---
id: 420
lang: en
translation_of: index.md
source_sha256: 8224c0dc8ae57cdabb3cf77718a6d148b1245afe3cd29a8f90d6452b4f45ec2e
title: "P2577: [ZJOI2005] Lunch — Solution"
description: "A DP over how many minutes the first i people spend in queue 1; the queue-2 dimension drops out since it equals the prefix sum minus j."
tags: ["OI","DP"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "Problem name 午餐 rendered as “Lunch”."
  - "The first display formula contains the Chinese 当 (“when”) outside any \\text{…}; TeX is kept identical, so it reads “when persons[i].a <= j”."
---

## Main Idea

It's easy to come up with the state $dp[i][j][k]$, the minimum time for the first $i$ people with $j$ minutes of queueing in queue 1 and $k$ minutes in queue 2. Then you notice that the $k$ dimension can be eliminated outright, since $k=sum[i]-j$. So once the linear dependency is eliminated, the equation becomes really <span class="slang" data-zh="小清新" data-gloss="xiǎo qīngxīn, “small and fresh”. Internet slang for something light, clean and pleasant; here: neat and simple.">refreshingly clean</span>:

$$
dp[i][j] = min\{dp[i][j], max\{dp[i - 1][j - persons[i].a], j + persons[i].b\}\},当persons[i].a\leq j
$$

$$
dp[i][j] = min\{dp[i][j], max\{dp[i - 1][j], sum[i] - j + persons[i].b\}\}
$$

## Code

```cpp
// P2577.cpp
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define ll long long
using namespace std;
const int MX_N = 220;
struct person
{
    ll a, b;
    bool operator<(const person &ps) const
    {
        return b > ps.b;
    }
} persons[MX_N];
ll sum[MX_N], n, dp[MX_N][MX_N * MX_N];
int main()
{
    scanf("%lld", &n);
    for (int i = 1; i <= n; i++)
        scanf("%lld%lld", &persons[i].a, &persons[i].b);
    sort(persons + 1, persons + 1 + n);
    for (int i = 1; i <= n; i++)
        sum[i] = sum[i - 1] + persons[i].a;
    memset(dp, 0x3f, sizeof(dp));
    dp[0][0] = 0;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= sum[i]; j++)
        {
            if (j >= persons[i].a)
                dp[i][j] = min(dp[i][j], max(dp[i - 1][j - persons[i].a], (ll)(j + persons[i].b)));
            dp[i][j] = min(dp[i][j], max(dp[i - 1][j], sum[i] - j + persons[i].b));
        }
    ll ans = 0x7fffffff;
    for (int i = 0; i <= sum[n]; i++)
        ans = min(ans, dp[n][i]);
    printf("%lld", ans);
    return 0;
}
```
