In this problem, you are given two permutations a and b of n numbers, and you need to play a game with them! In this game, you are required to perform the following steps:
For each number x, draw a line segment connecting between its positions in the given permutations.
Count the number of intersections between the line segments.
For example, let us consider two permutations (5, 4, 2, 1, 3) and (2, 5, 4, 1, 3). The following picture shows the permutations after drawing all line segments. In the picture, the number of intersections between the line segments is 2.
Given the permutations a and b, your task is to play the game and to count number of intersections between the line segments. Can you?
Input
The first line contains an integer T (1 ≤ T ≤ 100), in which T is the number of test cases.
The first line of each test case contains an integer n (1 ≤ n ≤ 105), in which n is the size of permutations.
Then a line follow containing n distinct integers a1, a2, …, an (1 ≤ ai ≤ n), giving the first permutation a.
Then a line follow containing n distinct integers b1, b2, …, bn (1 ≤ bi ≤ n), giving the second permutation b.
The sum of n overall test cases does not exceed 7 × 105.
Output
For each test case, print a single line containing the number of intersections between the line segments.
Example
Input
2
5
5 4 2 1 3
2 5 4 1 3
4
1 2 3 4
1 2 4 3
Output
2
1
下面代码是师兄给出的答案
题意:给出两个数组,数组里面是相同的数,然后相同的数之间连边,求有多少交点,交点重叠算多个点
思路:从第二个数组开始下手,考虑到当前位置,连边,如果之前的边连的点在当前点连的目标点的后面,就会产生一个点,也就是说统计一下之前有多少个点的目标点在目前这个点的目标点后面,树状数组处理一下
#include <bits/stdc++.h>
using namespace std;
#define N 100010
#define ll long long
int t, n;
int a[N], b[N];
int id[N];
int arr[N];
inline int lowbit(int x)
{
return x & (-x);
}
inline void update(int x, int val)
{
for (int i = x; i <= n; i += lowbit(i))
arr[i] += val;
}
inline int sum(int x)
{
int ans = 0;
for (int i = x; i; i -= lowbit(i))
ans += arr[i];
return ans;
}
int main()
{
scanf("%d", &t);
while (t--)
{
scanf("%d", &n);
for (int i = 1; i <= n; ++i)
scanf("%d", a + i), id[a[i]] = i;
for (int i = 1; i <= n; ++i)
scanf("%d", b + i);
memset(arr, 0, sizeof arr);
ll ans = 0;
for (int i = 1; i <= n; ++i)
{
int index = id[b[i]];
ans += sum(n) - sum(index);
update(index, 1);
}
printf("%lld\n", ans);
}
return 0;
}