H2. Maximum Crossings (Hard Version)

传送门

H2. Maximum Crossings (Hard Version)

time limit per test

1 second

memory limit per test

256 megabytes

input

standard input

output

standard output

The only difference between the two versions is that in this version n≤2⋅105n≤2⋅105 and the sum of nn over all test cases does not exceed 2⋅1052⋅105.

A terminal is a row of nn equal segments numbered 11 to nn in order. There are two terminals, one above the other.

You are given an array aa of length nn. For all i=1,2,…,ni=1,2,…,n, there should be a straight wire from some point on segment ii of the top terminal to some point on segment aiai of the bottom terminal. For example, the following pictures show two possible wirings if n=7n=7 and a=[4,1,4,6,7,7,5]a=[4,1,4,6,7,7,5].

H2. Maximum Crossings (Hard Version)_第1张图片

A crossing occurs when two wires share a point in common. In the picture above, crossings are circled in red.

What is the maximum number of crossings there can be if you place the wires optimally?

Input

The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases.

The first line of each test case contains an integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the array.

The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n) — the elements of the array.

The sum of nn across all test cases does not exceed 2⋅1052⋅105.

Output

For each test case, output a single integer — the maximum number of crossings there can be if you place the wires optimally.

Example

input

Copy

4
7
4 1 4 6 7 7 5
2
2 1
1
1
3
2 2 2

output

Copy

6
1
0
3

Note

The first test case is shown in the second picture in the statement.

In the second test case, the only wiring possible has the two wires cross, so the answer is 11.

In the third test case, the only wiring possible has one wire, so the answer is 00.

这题其实就是一个树状数组的模板题。

题目要求我们求最多的交点数目,我们可以从n反向遍历,如果此时树状数组中有几个小于当前对应的树,即有几个交点。

#define _CRT_SECURE_NO_DEPRECATE
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define lowbits(x) x&(-x)
using namespace std;
typedef long long ll;
typedef pair pii;
typedef pair pll;
const int inf = 0x3f3f3f3f;
const int mod = 1000000007;
const int N = 2e5 + 10;
ll a[N], b[N];
int n;
void update(int x) {
	while (x <= n) {
		b[x]++;
		x += lowbits(x);
	}
}
int getsum(int x) {
	ll ans = 0;
	while (x) {
		ans += b[x];
		x -= lowbits(x);
	}
	return ans;
}
int main() {
	int t;
	cin >> t;
	while (t--) {
		cin >> n;
		for (int i = 1; i <= n; i++) {
			cin >> a[i];
			b[i] = 0;
		}
		ll sum = 0;
		for (int i = n; i >= 1; i--) {
			sum += getsum(a[i]);
			update(a[i]);
		}
		cout << sum << endl;
	}
	return 0;
}

 

你可能感兴趣的:(算法)