题解:P12880 [蓝桥杯 2025 国 C] 数字配对
Rain_Mountain · · 题解
思路
看到这道题首先想到的思路:对于每个
Nevertheless,这样只能得 40pts。
hack:
5
1 4 2 3 2
显然,答案是 2 对,分别为
但按照刚才的思路,
考虑对于
-
`... x ... x+1(1) ... x+1(2) ... x+1(n) ...` $\because x+1(n)$ 到末尾的距离 $< x+1(n-1)$ 到末尾的距离 $ < \cdots < x+1(1)$ 到末尾的距离。 $\therefore P(x+1(n) $ 与 $x+2$ 配对的概率$) < P(x+1(n-1) $ 与 $x+2$ 配对的概率$) < \cdots < P(x+1(1) $ 与 $x+2$ 配对的概率$)$。 $\therefore$ 当 $x$ 与最后一个 $x+1$ 配对时,能最大概率地使其他的 $x+1$ 与 $x+2$ 配对。 -
综上,**当每次取的 $x$ 和 $x+1$ 都是同等数值中下标最靠后的数时,答案最优**。
\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。