题解:P12880 [蓝桥杯 2025 国 C] 数字配对

· · 题解

思路

看到这道题首先想到的思路:对于每个 a_i,找到后面第一个没用过的 a_i + 1。

Nevertheless,这样只能得 40pts。

hack:

5
1 4 2 3 2

显然,答案是 2 对,分别为 (1,2) 和 (2,3)。
但按照刚才的思路,1 会与第一个 2 配对,这样 2 和 3 就无法配对了。

考虑对于 A 中的一个 x:

\textit{\textbf Code}

#include <bits/stdc++.h>
using namespace std;

int n, a, s[1000005];
vector<int> v[1000005];

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    cin >> n;
    int x = 1e6 + 5, maxx = 0;
    for (int i = 1; i <= n; ++i)
    {
        cin >> a;
        v[a].push_back(i);
        ++s[a];
        x = min(x, a);
        maxx = max(maxx, a);
    }
    int ans = 0;
    while (x < maxx)
    {
        while (s[x] && s[x + 1])
        {
            if (v[x][s[x] - 1] > v[x + 1][s[x + 1] - 1]) --s[x];
            else
            {
                --s[x]; --s[x + 1];
                ++ans;
            }
        }
        ++x;
    }
    cout << ans;
    return 0;
}

求赞! qwq。