poj1990 (树状数组)

题意:给定n个猪的x坐标和它们的音量,2头猪之间的交谈声=他们之间的距离*他们间比较大的音量,求n头猪两两交谈的总音量。

把n头猪根据音量从小到大排后,用线段数组记录下他们的距离与猪的数量。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
const ll maxn = 20010;


struct node{
	ll x;
	ll v;
	bool operator<(const node& a) const{
	       return v<a.v;
	}
};

ll n,maxcount[maxn],maxdis[maxn];
node a[maxn];

ll lower_bit(ll x){
	return x&-x;
}

ll findd(ll x,ll *arr){
	ll ans = 0;
	while(x){
		ans += arr[x];
		x -= lower_bit(x);
	}
	return ans;
}

void add(ll x,ll y,ll *arr){
	while(x < maxn){
		arr[x] += y;
		x += lower_bit(x);
	}
}

ll solve(){
	ll ans = 0,count,dis,tdis = 0;
	memset(maxcount,0,sizeof(maxcount));
	memset(maxdis,0,sizeof(maxdis));
	sort(a,a+n);
	for(int i = 0;i<n;++i){
		count = findd(a[i].x,maxcount);
		dis = findd(a[i].x,maxdis);
		ans += a[i].v * (count*a[i].x - dis);
		ans += a[i].v * (tdis - dis - (i-count)*a[i].x);
		tdis += a[i].x;
		add(a[i].x,1,maxcount);
		add(a[i].x,a[i].x,maxdis);
	}
	return ans;
}

int main(){
	cin>>n;
	for(int i = 0;i<n;++i){
		cin>>a[i].v>>a[i].x;
	}
    cout<<solve()<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/dukig/article/details/89183798
今日推荐