题意
求有多少对 ,使得只经过 的点 能从 走到 。
分析
这种题在有两个变量时一般不太好下手,不妨从大到小枚举 ,注意到可行的 存在最大值,使得比该值大时均不可行,否则都可行。
那么可以类似双指针,考虑开一个 pos 数组存每个值的位置,先贪心找出 时最大的可行 ,当 时更新可行 的最大值,并在 不存在时直接退出,每次找到对应的最大 时令 即可,这个过程是容易的,时间复杂度 。
代码
可能逻辑写复杂了,不过能用。
namespace LCL {
constexpr int MAXN = 2e5 + 10, MAXV = MAXN << 2;
int n, L, R, a[3][MAXN], ans;
vpii pos[MAXN << 1];
void main() {
cin >> n;
rep(i, 1, n << 1) pos[i].clear();
rep(i, 1, 2) rep(j, 1, n) cin >> a[i][j], pos[a[i][j]].eb(i, j);
L = min(a[1][1], a[2][n]), R = n << 1, ans = 0;
rep(i, 1, n - 1) {
if (a[1][i] >= L && a[2][i] >= L)
chkmn(L, max(a[1][i + 1], a[2][i + 1]));
else if (a[1][i] >= L)
chkmn(L, max(a[1][i + 1], min(a[2][i], a[2][i + 1])));
else
chkmn(L, max(a[2][i + 1], min(a[1][i], a[1][i + 1])));
}
ans = L, debug("L = %lld, R = %lld\n", L, R);
while (--R >= max(a[1][1], a[2][n])) {
for (auto [x, y] : pos[R + 1]) {
if (a[3 - x][y] > R) return cout << ans << endl, void();
chkmn(L, a[3 - x][y]);
if (y > 1) {
if (a[3 - x][y - 1] > R) return cout << ans << endl, void();
chkmn(L, a[3 - x][y - 1]);
}
if (y < n) {
if (a[3 - x][y + 1] > R) return cout << ans << endl, void();
chkmn(L, a[3 - x][y + 1]);
}
}
if (L > R) break;
ans += L;
debug("L = %lld, R = %lld\n", L, R);
}
cout << ans << endl;
}
} // namespace LCL