Poj 3928 Ping pong 树状数组

本文介绍了一种使用C++实现的能力匹配算法,通过排序、二分查找和差分数组等技术解决能力匹配问题。算法的时间复杂度为O(nlogn),空间复杂度为O(n)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接


#include <stdio.h>
#include <string.h>
#include <math.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn = 100005;
const int Mod = 1000000007;
int n;
int c[maxn<<2];
struct Node
{
	int id,k;
}node[maxn];
bool cmp( Node a,Node b )
{
	return a.k < b.k;
}
int lowbit( int x )  
{  
	return x&(-x);  
}  
void add( int x )  
{  
	while( x <= n )  
	{  
		c[x] += 1;  
		x += lowbit(x);  
	}  
}  

int sum( int x )  
{  
	int ans = 0;  
	while( x >= 1 )  
	{  
		ans += c[x];  
		x -= lowbit(x);  
	}  
	return ans;  
} 
int main()
{
#ifndef ONLINE_JUDGE     
	freopen("data.txt","r",stdin);     
#endif  
	int cas;
	scanf("%d",&cas);
	while( cas -- )
	{
		LL ans = 0,ld,rd;
		scanf("%d",&n);
		memset( c,0,sizeof(c) );
		for( int i = 1; i <= n; i ++ )
		{
			scanf("%d",&node[i].k);  
			node[i].id = i;
		}
		sort( node+1,node+n+1,cmp );
		for( int i = 1; i <= n; i ++ )
		{
			ld = sum( node[i].id );     //能力小于i且下标下与i的个数
			rd = i-1 - ld;              //能力小于i但下标大于i的个数
			ans += ( ld*( n-node[i].id - rd ) ) + rd*( node[i].id - ld - 1 );
			add( node[i].id );
		}
		printf("%I64d\n",ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值