Tufurama CodeForces - 961E (cdq分治)

题面
One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused — what if he decides to rewatch the entire series someday and won't be able to find the right episodes to watch? Polycarp now wants to count the number of times he will be forced to search for an episode using some different method.
题意
求a[i]>=j并且a[j]>=i的对数
思路
二维偏序问题,试图使用数状数组解决.
但是有些对会重复计算,所以加上限制条件,i<j
这便是一个三维偏序问题.

#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>

#define fuck(x) cerr<<#x<<" = "<<x<<endl;
#define debug(a, x) cerr<<#a<<"["<<x<<"] = "<<a[x]<<endl;
#define lson l,mid,ls
#define rson mid+1,r,rs
#define ls (rt<<1)
#define rs ((rt<<1)|1)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int loveisblue = 486;
const int maxn = 400086;
const int maxm = 100086;
const int inf = 0x3f3f3f3f;
const ll Inf = 999999999999999999;
const int mod = 1000000007;
const double eps = 1e-6;
const double pi = acos(-1);

struct node{
    int f,x,y,z;
}a[maxn],tmp[maxn];

int bit[maxn];
int lowbit(int x) {
    return x & -x;
}

int query(int pos) {
    int ans = 0;
    while (pos) {
        ans += bit[pos];
        pos -= lowbit(pos);
    }
    return ans;
}

void update(int pos,int val){
    while(pos<maxn){
        bit[pos]+=val;
        pos+=lowbit(pos);
    }
}
ll ans ;

void cdq(int l,int r){
    if(l==r){ return;}
    int mid = (l+r)>>1;
    cdq(l,mid);cdq(mid+1,r);

    int t1=l,t2=mid+1;
    int cnt = l-1;
    while (t1<=mid||t2<=r){

        if(t2>r||(t1<=mid&&a[t1].y<=a[t2].y)){
            if(a[t1].f==1){
                update(a[t1].z,1);
            }
            tmp[++cnt]=a[t1];
            t1++;

        }else{
            if(a[t2].f==0){
                ans+=query(maxn-5)-query(a[t2].z-1);
            }
            tmp[++cnt]=a[t2];
            t2++;
        }
    }for(int i=l;i<=mid;i++){
        if(a[i].f==1){
            update(a[i].z,-1);
        }
    }
    for(int i=l;i<=r;i++){
        a[i]=tmp[i];
    }

}


int main() {
    ios::sync_with_stdio(true);
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
#endif

    int n;
    scanf("%d",&n);
    int tot= 0;
//    int ans=  0;
    for(int i=1;i<=n;i++){
        int x;
        scanf("%d",&x);
        x=min(x,n);
        a[++tot]=node{0,i,x,i};
        a[++tot]=node{1,i,i,x};
//        if(i==x){ans--;}
    }

    cdq(1,tot);
    printf("%lld\n",ans);

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/ZGQblogs/p/11465808.html