Problem Description
Recently, dobby is addicted in the Fruit Ninja. As you know, dobby is a free elf, so unlike other elves, he could do whatever he wants.But the hands of the elves are somehow strange, so when he cuts the fruit, he can only make specific move of his hands. Moreover, he can only start his hand in point A, and then move to point B,then move to point C,and he must make sure that point A is the lowest, point B is the highest, and point C is in the middle. Another elf, Kreacher, is not interested in cutting fruits, but he is very interested in numbers.Now, he wonders, give you a permutation of 1 to N, how many triples that makes such a relationship can you find ? That is , how many (x,y,z) can you find such that x < z < y ?
Input
The first line contains a positive integer T(T <= 10), indicates the number of test cases.For each test case, the first line of input is a positive integer N(N <= 100,000), and the second line is a permutation of 1 to N.
Output
For each test case, ouput the number of triples as the sample below, you just need to output the result mod 100000007.
Sample Input
2 6 1 3 2 6 5 4 5 3 5 2 4 1
Sample Output
Case #1: 10Case #2: 1
统计满足条件的(x,y,z)的个数,由于直接统计100%超时,所以应该转化一下。
从整体上看,先求出x<y<z和x<z<y的总和有多少,在算出x<y<z有多少,相减就是答案了。
n<=100000,所以求和的时候用树状数组。
#include<iostream> #include<algorithm> #include<math.h> #include<cstdio> #include<string> #include<string.h> using namespace std; const int maxn = 100005; const int low(int x){ return (x&-x); } const int base = 100000007; int a[maxn]; int t, n, m, p; long long tot, sumt; void add(int x) { for (int i = x; i <= n; i += low(i)) a[i]++; } long long sum(int x) { long long total = 0; for (int i = x; i > 0; i -= low(i)) total += a[i]; return total; } int main(){ while (~scanf("%d", &t)) { int p = 0; while (++p <= t) { cin >> n; memset(a, 0, sizeof(a)); tot = sumt = 0; for (int i = 1; i <= n; i++) { scanf("%d", &m); add(m); long long c = n - m - i + sum(m); sumt = (sumt + c*(c - 1) / 2) % base; tot = (tot + c*(sum(m) - 1)) % base; } cout << "Case #" << p << ": " << (sumt - tot + base) % base << endl; } } return 0; }