比赛的时候是用线段树写的,赛后看了题解发现还有单调队列这种操作。
官方题解:
想学习单调队列可以看下这篇博客:点击打开链接
代码如下:
#include <bits/stdc++.h>
using namespace std;
typedef long long int LL;
const int MAX_N = 250005;
const int MOD = 1e9 + 7;
struct Node
{
int pos;
int minval;
};
deque<Node> que;
int main()
{
//freopen("test.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
cin.sync_with_stdio(false);
int n;
int a[MAX_N];
int b[MAX_N];
while (cin >> n)
{
que.clear();
for (int i = 1; i <= n; i++)
{
cin >> a[i];
a[i] -= i;
while (!que.empty() && a[i] > que.back().minval)
que.pop_back();
que.push_back({i, a[i]});
}
for (int i = 1; i <= n; i++)
cin >> b[i];
sort(b + 1, b + n + 1);
int ans = 0;
for (int i = 1; i <= n; i++)
{
while (!que.empty() && b[i] > que.front().pos)
que.pop_front();
int tmp = que.front().minval;
ans = (ans + tmp) % MOD;
tmp -= i + n;
while (!que.empty() && tmp > que.back().minval)
que.pop_back();
que.push_back({i + n, tmp});
}
cout << ans << endl;
}
return 0;
}