PAT TOP 1009. Triple Inversions (35)

本文介绍了一种高效算法来解决计数三元逆序对的问题,即在一个整数序列中找出所有满足条件i<j<k且Ai>Aj>Ak的三元组数量。文章通过分析给出一种创新的方法,利用数据结构进行优化,最终实现快速计算。

问题描述:

1009. Triple Inversions (35)

时间限制
300 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CAO, Peng

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

总感觉这一题又像是 最大不下降子列 的变形题。。。

先对每个输入的数分别求 它前面比它大的元素的个数r 和 它后面比它小的元素的个数b 两者相乘叠加就AC了;

AC代码(今天学习了平板电视(pb_ds)的相关知识,于是今天的代码变成了(pb_ds)风格的了。。。)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
int main()
{
//	freopen("data.txt","r",stdin);
	tree<long long,null_type,less<long long>,rb_tree_tag,tree_order_statistics_node_update> tr;
	long long n,x,s=0;
	long long r,b;
	scanf("%lld",&n);
	for(long long i=1;i<=n;i++)
	{
		scanf("%lld",&x);
		tr.insert(x);
		r=tr.size()-tr.order_of_key(x)-1;
		b=r-i+x;
		s=s+r*b;
	}
	printf("%lld",s);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值