题目 | Insert 1, Insert 2, Insert 3, ...
2023牛客暑期多校训练营8
H - Insert 1, Insert 2, Insert 3, ...
https://ac.nowcoder.com/acm/contest/57362/H
题意
给定长度为
题解
思路
一个合法的区间一定以
对于一个数
数字顶上标记相同的代表匹配为一组,可以看到最后一个
如果匹配上了,那答案的数量如何计算。对于每个匹配的一组数,找到它们起点(也就是
对于第一个
不过有一个要点是,如果有一个不合法的数将序列分开,那么左边的
对于最后一个
维护方式
使用 vector
而不是 stack
,要不然 MLE)维护每个数的位置,对于一个数
对于
代码
#include <bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
constexpr int MAXN = 1e6 + 10;
vector<int> p[MAXN], s;
void solve()
{
int n;
cin >> n;
int ans = 0;
for (int i = 1; i <= n; i++)
{
int x;
cin >> x;
if (x == 1)
{
p[1].push_back(i);
s.push_back(i);
ans += s.size();
}
else if (p[x - 1].empty())
{
s.clear();
}
else
{
int y = p[x - 1].back();
p[x - 1].pop_back();
p[x].push_back(y);
while (s.size() && s.back() > y)
s.pop_back();
ans += s.size();
}
}
cout << ans << endl;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t = 1;
// cin >> t;
while (t--)
solve();
return 0;
}
本文采用 CC BY-SA 4.0 许可,本文 Markdown 源码:Haotian-BiJi