Newcoder 4 A.Contest(逆序对-BIT)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/V5ZSQ/article/details/83618321

Description

n n 支队伍一共参加了三场比赛。

一支队伍 x x 认为自己比另一支队伍 y y 强当且仅当 x x 在至少一场比赛中比 y y 的排名高。

求有多少组 ( x , y ) (x,y) ,使得 x x 自己觉得比 y y 强, y y 自己也觉得比 x x 强。

$ (x, y), (y, x)$算一组。

Input

第一行一个整数 n n ,表示队伍数; 接下来 n n 行,每行三个整数 a [ i ] , b [ i ] , c [ i ] a[i], b[i], c[i] ,分别表示 i i 在第一场、第二场和第三场比赛中的名次; n n 最大不超过 200000 200000

Output

输出一个整数表示满足条件的 ( x , y ) (x,y) 数; 64 b i t 64bit 请用 l l d lld

Sample Input

4
1 3 1
2 2 4
4 1 2
3 4 3

Sample Output

5

Solution

( x , y ) (x,y) 之间必然是 x x 两败一胜或两胜一败,考虑因 a , b , c a,b,c 其中之一败因 a , b , c a,b,c 其中另一胜的二元组个数之和(即二元组逆序对个数),那么一组合法解 ( x , y ) (x,y) 会被计算四次,所求答案除以四即为答案,时间复杂度 O ( n l o g n ) O(nlogn)

Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=200005;
struct BIT 
{
	#define lowbit(x) (x&(-x))
	int b[maxn],n;
	void init(int _n)
	{
		n=_n;
		for(int i=1;i<=n;i++)b[i]=0;
	}
	void update(int x,int v)
	{
		while(x<=n)
		{
			b[x]+=v;
			x+=lowbit(x);
		}
	}
	int query(int x)
	{
		int ans=0;
		while(x)
		{
			ans+=b[x];
			x-=lowbit(x);
		}
		return ans;
	}
}bit;
int n,x[3][maxn];
P a[maxn];
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%d%d%d",&x[0][i],&x[1][i],&x[2][i]);
	ll ans=0;
	for(int i=0;i<3;i++)
		for(int j=0;j<3;j++)
			if(i!=j)
			{
				for(int k=1;k<=n;k++)a[k]=P(x[i][k],x[j][k]);
				sort(a+1,a+n+1);
				bit.init(n);
				for(int k=n;k>=1;k--)
				{
					ans+=bit.query(a[k].second);
					bit.update(a[k].second,1);
				}
			}
	printf("%lld\n",ans/4);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/V5ZSQ/article/details/83618321