题解:
直接用CDQ分治是O(nlog^2n)的,似乎可以过。
一种O(nlogn)的做法,考虑补集转化,答案 = 总对数 - 不满足条件的对数。
考虑不满足条件的数的性质,这一对数在其中两个排列里的位置关系是相同的,在另一个排列里的位置关系相反。
那么统计两两排列之间不满足偏序关系的数对的个数,这样统计下来每对数都被统计了两次,除以2就是不满足条件的对数。
如何统计?
用树状数组维护。
考虑下面这种情况,对于数对(x, y)
第一个排列:_x_u_y___k
第二个排列:___y_____x
(u与y下标相同,k与x下标相同)
我们从后向前遍历第一个排列。在遍历到k的时候,查询一下在第一个排列里x位置之前的前缀和,然后再在第一个排列里x位置+1。
遍历到u时,查询一下第一个排列里y位置之前的前缀和(这样就统计到了x位置上的1),然后再在第一个排列里y位置+1。
复杂度:
时间复杂度:O(nlogn),空间复杂度:O(n)。
WA:
n * (n - 1)忘了加(LL)。
GET:
神题...
/* Telekinetic Forest Guard */
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 200005;
typedef long long LL;
int n, A[maxn], B[maxn], C[maxn], tr[maxn], pos[maxn];
inline int iread() {
int f = 1, x = 0; char ch = getchar();
for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
return f * x;
}
inline void add(int x, int c) {
for(; x <= n; x += x & -x) tr[x] += c;
}
inline LL query(int x) {
LL res = 0;
for(; x; x -= x & -x) res += tr[x];
return res;
}
inline LL solve(int *x, int *y) {
LL res = 0;
for(int i = 1; i <= n; i++) pos[x[i]] = i, tr[i] = 0;
for(int i = n; i; i--) res += query(pos[y[i]]), add(pos[y[i]], 1);
return res;
}
int main() {
n = iread();
for(int i = 1; i <= n; i++) A[i] = iread();
for(int i = 1; i <= n; i++) B[i] = iread();
for(int i = 1; i <= n; i++) C[i] = iread();
LL ans = (LL)n * (n - 1);
ans -= solve(A, B) + solve(A, C) + solve(B, C);
printf("%lld\n", ans >> 1);
return 0;
}