---
id: 745
lang: en
translation_of: index.md
source_sha256: 6736d7508f39091498261e69cc7b355f490c15487e0d421cfc4146714452d043
title: "P1108: Buy Low, Buy Lower — Solution"
description: "The first part is an O(n^2) longest decreasing subsequence DP; the second stores the number of ways in an array g[] and removes duplicates."
tags: ["OI","DP"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "Problem name 低价购买 (literally “buying at a low price”) rendered with the original USACO English title “Buy Low, Buy Lower”."
  - "The Chinese words 当 (“when”) and 且 (“and”) inside the TeX are not in \\text{…}, so they are kept verbatim as part of the math."
---

## Main Idea

The first question is still pretty easy to answer: use $O(n^2)$ time to do the DP for the longest decreasing subsequence. For the second question, we can set up an array $g[]$ to store the number of ways. The transition equation can be derived quite obviously as:

$$
g[i] = \sum_{j = 1}^{i-1} g[j], 当 f[i] = f[j] + 1 且 arr[i]<arr[j]
$$

But we still need to remove duplicates. Suppose we have already counted the cases transferred from earlier; then we need to eliminate the earlier equivalent states, that is, eliminate the $j$-th term satisfying $f[j] == f[i] 且 arr[i] == arr[j]$. Here is the code:

## Code

```cpp
// P1108.cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 5050;
int n, arr[MAX_N], f[MAX_N], g[MAX_N], tot;
bool cmp(int a, int b) { return a > b; }
int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        scanf("%d", &arr[i]);
    for (int i = 1; i <= n; i++)
    {
        f[i] = 1;
        for (int j = 1; j < i; j++)
            if (arr[j] > arr[i])
                f[i] = max(f[j] + 1, f[i]);
        tot = max(tot, f[i]);
    }
    for (int i = 1; i <= n; i++)
    {
        if (f[i] == 1)
            g[i] = 1;
        for (int j = 1; j < i; j++)
        {
            if (f[i] == f[j] && arr[i] == arr[j])
                g[j] = 0;
            if (f[i] == f[j] + 1 && arr[j] > arr[i])
                g[i] += g[j];
        }
    }
    long long ans = 0;
    for (int i = 1; i <= n; i++)
        if (f[i] == tot)
            ans += g[i];
    printf("%d %lld", tot, ans);
    return 0;
}
```
