离散化+单点更新+区间求和

https://codeforces.com/contest/1311/problem/F

题意:在坐标轴上有n个点,每个点在xi位置(不会重叠),且具有vi的固定速度,问所有对点之间的最短距离之和。

解法:可分析得当xi > yi && vi > yi 得最短距离为xi-yi,其他情况均为0.

以x排序,统计比xi小得坐标且速度比vi小的个数sum1和坐标和sum2。

该点贡献可算的sum1*xi - sum2 .因为v的范围较大所以要离散化。

#include<bits/stdc++.h>
typedef long long ll ;
#define int ll
#define mod 1000000007
#define gcd __gcd
#define rep(i , j , n) for(int i = j ; i <= n ; i++)
#define red(i , n , j)  for(int i = n ; i >= j ; i--)
#define ME(x , y) memset(x , y , sizeof(x))
//ll lcm(ll a , ll b){return a*b/gcd(a,b);}
//ll quickpow(ll a , ll b){ll ans=1;while(b){if(b&1)ans=ans*a%mod;b>>=1,a=a*a%mod;}return ans;}
//int euler1(int x){int ans=x;for(int i=2;i*i<=x;i++)if(x%i==0){ans-=ans/i;while(x%i==0)x/=i;}if(x>1)ans-=ans/x;return ans;}
//const int N = 1e7+9; int vis[n],prime[n],phi[N];int euler2(int n){ME(vis,true);int len=1;rep(i,2,n){if(vis[i]){prime[len++]=i,phi[i]=i-1;}for(int j=1;j<len&&prime[j]*i<=n;j++){vis[i*prime[j]]=0;if(i%prime[j]==0){phi[i*prime[j]]=phi[i]*prime[j];break;}else{phi[i*prime[j]]=phi[i]*phi[prime[j]];}}}return len}
#define SC scanf
#define INF  0x3f3f3f3f
#define PI acos(-1)
#define pii pair<int,int>
#define fi first
#define se second
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
using namespace std;
const int maxn = 2e5+9;
const int N = 10000 ;
int s1[maxn] , s2[maxn];
pii a[maxn];
int b[maxn] , len;
int lowerbit(int x){
    return x&(-x);
}
void add(int x , int val){
    while(x <= len){
        s1[x]++;
        s2[x] += val;
        x += lowerbit(x);
    }
}
int getsum(int x , int s[]){
    int ans = 0 ;
    while(x){
        ans += s[x];
        x -= lowerbit(x);
    }
    return ans ;
}
void solve(){
    int n ;
    cin >> n ;
    rep(i , 1 , n){
        cin >> a[i].fi ;
    }
    rep(i , 1 , n){
        cin >> a[i].se;
        b[i] = a[i].se;
    }
    int ans = 0 ;
    sort(b + 1 , b + 1 + n);
    sort(a + 1 , a + 1 + n);
    len = unique(b + 1 , b + 1 + n) - b - 1 ;
    rep(i , 1 , n){
        int pos = lower_bound(b + 1 , b + 1 + len , a[i].se) - b ;
        int sum1 = getsum(pos , s1) , sum2 = getsum(pos , s2);
        ans += sum1 * a[i].fi - sum2 ;
        add(pos , a[i].fi);
    }
    cout << ans << endl;

}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    //int t ;
    //cin >> t ;
    //while(t--){
        solve();
    //}
}

 

posted @ 2020-03-01 00:37  无名菜鸟1  阅读(219)  评论(0编辑  收藏  举报