luogu2345 奶牛机会 树状数组, O(n*logn)

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring> 
using namespace std;
struct Cow{
	long long v, x;
	int id;
}cow[20002];
int n;     // cnt 记录删点的个数       
long long sum_x[20002], cnt[20002], ans; 

bool cmp1(Cow a, Cow b){	return a.x < b.x; }

bool cmp(Cow a, Cow b) { return a.v > b.v;  }

void add(int x, long long val, long long *p)
{
	while (x <= n) {
		p[x] += val;
		x += x&(-x);
	}
}

long long get_sum(int x, long long *p)
{
	long long re = 0;
	while (x) {
		re += p[x];
		x -= x&(-x);
	}
	return re;
}

int main()
{
	scanf("%d", &n);
	for (int i=1; i<=n; i++) scanf("%lld %lld", &cow[i].v, &cow[i].x);
	
	sort(cow+1, cow+n+1, cmp1);
	for (int i=1; i<=n; i++) add(i, cow[i].x, sum_x);
	for (int i=1; i<=n; i++) cow[i].id = i;
	sort(cow+1, cow+1+n, cmp);
	
	int now_x, id, now_v;
	for (int i=1; i<=n; i++) {
		now_x = cow[i].x;
		now_v = cow[i].v;
		id = cow[i].id;
		ans = ans + ( now_x*(id-1 + get_sum(id-1, cnt)) - get_sum(id-1, sum_x)  
		+  get_sum(n, sum_x) - get_sum(id, sum_x) - now_x*( n-id + (get_sum(n, cnt) - get_sum(id, cnt)) )  ) 
		* now_v;
		add(id, -1ll, cnt);
		add(id, -1ll*now_x, sum_x);
	} 
	cout<<ans<<endl;
}

注意:cnt 是 -1 的修改, cnt 求和前是加号

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值