PAT 1009. Triple Inversions (35) 数状数组

时间:2024-12-02 18:07:25

Given a list of N integers A1, A2, A3,...AN, there's a famous problem to count the number of inversions in it. An inversion is defined as a pair of indices i < j such that Ai > Aj.

Now we have a new challenging problem. You are supposed to count the number of triple inversions in it. As you may guess, a triple inversion is defined as a triple of indices i < j < k such that Ai > Aj > Ak. For example, in the list {5, 1, 4, 3, 2} there are 4 triple inversions, namely (5,4,3), (5,4,2), (5,3,2) and (4,3,2). To simplify the problem, the list A is given as a permutation of integers from 1 to N.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N in [3, 105]. The second line contains a permutation of integers from 1 to N and each of the integer is separated by a single space.

Output Specification:

For each case, print in a line the number of triple inversions in the list.

Sample Input:

22
1 2 3 4 5 16 6 7 8 9 10 19 11 12 14 15 17 18 21 22 20 13

Sample Output:

8

题意:给定1~n的无序数列,求其中长度=3连续递减的字串个数,如样例:(16,14,13)。
思路:愚蠢!愚蠢!刚开始找的是三个数中的最前一个,然而判断连续递减就有点困难(这题时间限制为300ms)。
其实可以找中间的那个数,再向左查询比中间数大的数的个数,向右查询比中间数小的个数, 两侧相乘就是解了。
最大的问题是如何记录大小,因为给定的是1~n连续的数,甚至不需用离散化,通过遍历到某个数,找比它小或大的是否已经被标记了,再标记这个数。
快速求和操作显然要用到树状数组。
噢,还有这题注意结果使用long long 为此而WA。
 #include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
#define LL long long
using namespace std; int n, c[], a[];
LL l[], r[];
void add(int x) //增加操作
{
while(x <= n)
{
c[x]++;
x += x & (-x);
}
} int get(int x) //获取和
{
int ans = ;
while(x)
{
ans +=c[x];
x -= x & (-x);
}
return ans;
}
int main()
{
LL ans;
while(cin >> n)
{
ans = ;
for(int i = ; i <= n; i++)
{
scanf("%d", a + i);
c[i] = ;
}
for(int i = ; i <= n; i++)
{
l[i] = i - - get(a[i]);
add(a[i]);
}
for(int i = ; i <= n; i++)
c[i] = ;
for(int i = ; i <= n; i++)
{
r[i] = a[i] - - get(a[i]);//为value - 左侧大于它的个数
add(a[i]);
} for(int i = ; i <= n; i++)
ans += l[i]*r[i]; printf("%lld\n", ans);
}
}