luogu P2345 cows rally | sort + Fenwick tree

Title Description

John N cows every year participate in the "moo of the General Assembly." Assembly cows moo community event. Many activities on rallies, such as hay stack, across the fence, touching cowboy ass and so on. They converge together to participate in activities, the coordinates of the i-th cows Xi, two cows coordinates are not the same. Cows sounds great, the i-th and j cows head exchange, will be issued max {Vi; Vj} × | Xi - Xj | volume, where Vi and Vj are the i-th and j-th head of cows hearing.

Assuming that between each pair of cows are talking at the same time, calculate the volume of all cows to produce and how much.

Input Format

• First line: single integer N, 1 ≤ N ≤ 20000

• second row to row 1 + N: i + 1 of two integers line Vi and Xi, 1 ≤ Vi ≤ 20000; 1 ≤ Xi ≤ 20000

Output Format

• a single integer: Indicates the volume of all cows produced and


#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#define ll long long
using namespace std;
const int N=2e4+1;
struct E{
    int v,x;
}e[N];
int n;
bool cmp(E t1,E t2){
    return t1.v<t2.v;
}
ll c1[N],c2[N];
void add1(int x,int y)
{
    for(;x<=N;x+=x&(-x))
    c1[x]+=y;
}
ll num1(int x)
{
    int ans=0;
    for(;x;x-=x&(-x))ans+=c1[x];
    return ans;
}
void add2(int x,int y)
{
    for(;x<=N;x+=x&(-x))
    c2[x]+=y;
}
ll num2(int x)
{
    int ans=0;
    for(;x;x-=x&(-x))ans+=c2[x];
    return ans;
}
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    scanf("%d%d",&e[i].v,&e[i].x);
    sort(e+1,e+1+n,cmp);
    ll ans=0;
    for(int i=1;i<=n;i++)
    {
        ll p1=num1(e[i].x),p2=num2(e[i].x);
        ans+=e[i].v*abs(e[i].x*p1-p2);
        p1=num1(N)-p1;p2=num2(N)-p2;
        ans+=e[i].v*abs(e[i].x*p1-p2);
        add1(e[i].x,1);
        add2(e[i].x,e[i].x);
    }
    cout<<ans<<endl;
}

Guess you like

Origin www.cnblogs.com/naruto-mzx/p/11854695.html