题目 | Moscow Gorillas
Codeforces Round 852 (Div. 2)
D. Moscow Gorillas
https://codeforces.com/problemset/problem/1793/D
2 seconds / 256 megabytes
standard input / standard output
Problem
In winter, the inhabitants of the Moscow Zoo are very bored, in particular, it concerns gorillas. You decided to entertain them and brought a permutation
A permutation of length
The gorillas had their own permutation
The
You do not want to risk your health, so you will not dare to refuse the gorillas.
Input
The first line contains a single integer
The second line contains
The third line contains
Output
Print a single integer — the number of suitable pairs
Examples
Input
3
1 3 2
2 1 3
Output
2
Input
7
7 3 6 2 1 5 4
6 7 2 5 3 1 4
Output
16
Input
6
1 2 3 4 5 6
6 5 4 3 2 1
Output
11
Note
In the first example, two segments are correct –
In the second example, for example, the segment
题解
首先,我们从
我们找区间时,也是从
首先我们找到
- 情况一:
这种情况的例子如下(为了示例更清晰,无关信息用点代替。第一行为下标):
i | 1 2 3 4 5 6 7 8
-------------------
p | . 1 . . . . 2 .
q | . . 1 . 2 . . .
若一个区间的
所以满足这种情况的区间数为:
- 情况二:
这种情况的例子如下:
i | 1 2 3 4 5 6 7 8
-------------------
p | . . 2 . . 1 . .
q | . 2 . . . . 1 .
满足这种情况的区间数为:
- 情况三:
且
这种情况非常容易漏掉,导致这道题后面的测试点过不去,例子如下:
i | 1 2 3 4 5 6 7 8
-------------------
p | . 2 . 1 . . . .
q | . . . . 1 . . 2
由于这种情况
满足这种情况的区间数为:
- 其他情况
除了上述三种情况,其他情况均不成立,即答案是
上面是从
另外还需要额外
找到
代码
#include <bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
void solve()
{
int n;
cin >> n;
vector<int> rp(n + 10), rq(n + 10);
for (int i = 1; i <= n; i++)
{
int t;
cin >> t;
rp[t] = i;
}
for (int i = 1; i <= n; i++)
{
int t;
cin >> t;
rq[t] = i;
}
int pmin = min(rp[1], rq[1]), pmax = max(rp[1], rq[1]);
int ans = (n - pmax) * (n - pmax + 1) / 2 +
(pmin - 1) * pmin / 2 +
(pmax - pmin - 1) * (pmax - pmin) / 2 + 1;
for (int i = 2; i <= n; i++)
{
int mn = min(rp[i], rq[i]);
int mx = max(rp[i], rq[i]);
if (pmax < mn)
ans += (mn - pmax) * pmin;
else if (mx < pmin)
ans += (pmin - mx) * (n - pmax + 1);
else if (mn < pmin && mx > pmax)
ans += (pmin - mn) * (mx - pmax);
pmax = max(pmax, mx);
pmin = min(pmin, mn);
if (pmax == n && pmin == 1)
break;
}
cout << ans << endl;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
solve();
return 0;
}
本文采用 CC BY-SA 4.0 许可,本文 Markdown 源码:Haotian-BiJi