---
id: 1207
lang: en
translation_of: index.md
source_sha256: 8ad5ed133d32e784d57bc13fe69cfdc7f8b06da391ffc7f97c5b9bcb128a3409
title: "BZOJ2298: [HAOI2011] problem a — Solution"
description: "This DP problem is very well set: it tests a contestant's ability to transform the model."
tags: ["OI","DP","Linear DP"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "The source has two typos, 对一每一种 (for 对于每一种, “for every”) and 以坐标位关键字 (for 以坐标为关键字, “keyed by coordinate”); translated as intended."
  - "The problem name “problem a” is kept as in the original title."
---

## Solution

This DP problem is very well set: it tests a contestant's ability to transform the model.

> Person $i$ says: “There are $ai$ people who scored higher than me, and $bi$ people who scored lower than me.”

Each statement can be seen as a segment $[a_i+1,n-b_i]$ on a one-dimensional coordinate line, meaning the people on this segment have equal scores. Clearly, in every valid case these segments do not intersect (complete overlap is allowed). So sort the segments by left endpoint, and this $dp$ equation, keyed by coordinate, should be written as:

$$
dp[i] = dp[i-l] + min(\text{segment length}, \text{number of segments})
$$

<!--more-->

## Code

```cpp
// BZ2298.cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 101000;
int n, dp[MAX_N], cnt;
struct pr
{
    int first, second;
    bool operator<(const pr &p) const
    {
        return second < p.second || (second == p.second && first < p.first);
    }
} res[MAX_N];
int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
    {
        int x, y;
        scanf("%d%d", &x, &y);
        if (x + y < n)
            res[++cnt].first = x + 1, res[cnt].second = n - y;
    }
    sort(res + 1, res + 1 + cnt);
    int cur = 1;
    for (int i = 1; i <= n; i++)
    {
        dp[i] = dp[i - 1];
        int tmp = 0;
        while (res[cur].second < i)
            cur++;
        for (; res[cur].second == i; cur++)
        {
            if (res[cur].first == res[cur - 1].first)
                tmp++;
            else
                tmp = 1;
            dp[i] = max(dp[i], dp[res[cur].first - 1] + min(tmp, i - res[cur].first + 1));
        }
    }
    printf("%d", n - dp[n]);
    return 0;
}
```
