[luogu] P2345 MooFest G 树状数组

前言

传送门 :

思路

很好的一个 树状数组入门题

我们可以通过树状数组维护 s u m sum sum c n t cnt cnt最后计算出答案

CODE

struct node
{
	int v,x;
	bool operator < (const node &w){
		return v<w.v;
	}
}cow[N];

ll ans,sum[N],cnt[N];

int lowbit(int x)
{
	return x&-x;
}

void add(int x,int k)
{
	for(;x<=N;x+=lowbit(x))
	sum[x]+=k,cnt[x]+=1;
}

void query(int x,ll &p1,ll &p2)
{
	p1 = 0 ;
	p2 = 0;
	for(;x;x-=lowbit(x))
	p1+=sum[x],p2+=cnt[x];
}
void solve()
{
	cin>>n;
	for(int i =1;i<=n;i++)
	cin>>cow[i].v>>cow[i].x;
	
	sort(cow+1,cow+1+n);
	
	ll s1 = 0 ,c1 = 0 ;
	
	for(int i=1;i<=n;i++)
	{
		ll s2 = 0 ,c2 = 0 ;
		query(cow[i].x,s2,c2);
		
		ans+=cow[i].v *(c2 * cow[i].x - s2);
		ans+=cow[i].v *((s1-s2)-(c1-c2)*cow[i].x);
		add(cow[i].x,cow[i].x);
		s1+=cow[i].x;
		c1+=1;
	}
	cout<<ans<<endl;
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值