题目
题目链接:http://codeforces.com/contest/689/problem/D
题目来源:Codeforces#361
题解
考虑左边起点固定,则随着右边终点向右移动, a 最大值单调不递减,
b 最小值单调不递增。利用这个性质我们可以知道 a 最大值和
b 最小值在同一起点情况下只有一段。可以利用一些数据结构求区间最值然后二分相等的一段。
更好的方法就是利用尺取法,不断移动终点,求出符合条件的一段。
第一次用
multiset
被坑了,要注意erase
会删掉所有的。
代码
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <set>
#include <map>
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
// head
const int N = 2e5+5;
int a[N], b[N];
multiset<int> sa[2], sb[2];
void eraseOne(multiset<int> &m, int v) {
m.erase(m.find(v));
}
int main() {
int n;
while (scanf("%d", &n) == 1) {
for (int i = 0; i < n; i++) {
scanf("%d", a+i);
}
for (int i = 0; i < n; i++) {
scanf("%d", b+i);
}
LL ans = 0;
int r0 = n-1, r1 = r0;
for (int i = n-1; i >= 0; i--) {
sa[0].insert(a[i]);
sa[1].insert(a[i]);
sb[0].insert(b[i]);
sb[1].insert(b[i]);
while (!sa[0].empty() && *sa[0].rbegin() > *sb[0].begin()) {
eraseOne(sa[0], a[r0]);
eraseOne(sb[0], b[r0--]);
}
while (!sa[1].empty() && *sa[1].rbegin() >= *sb[1].begin()) {
eraseOne(sa[1], a[r1]);
eraseOne(sb[1], b[r1--]);
}
ans += r0 - r1;
}
printf("%I64d\n", ans);
for (int i = 0; i < 2; i++) {
sa[i].clear();
sb[i].clear();
}
}
return 0;
}