P1637题解 (cdq分治做法)

· · 题解

明明只需要1次cdq,题解里面只有2次的。(可恶遗憾的是该题目已不接受新题解)

思路

原数据用结构体存,主要为了记录每个数据原来的位置:

struct Node{
    //v值,pos位置
    int v,pos;
    //重载 < 是因为后面要使用lower_bound
    bool operator < (const Node b) const {
        return v < b.v;
    }
}a[maxn],tmp[maxn];

可以用两个数组分别存左侧严格小于a[i]的数量和右侧严格大于a[i]的数量。统计过程采用cdq分治,这里使用lower_bound大法就只需要1次就能全部求解啦:

void cdq(int x,int y){
    if(x >= y) return;
    int mid = (x+y)/2;
    cdq(x,mid);cdq(mid+1,y);
    int l = x,r = mid+1,cnt = 0;
    while(l <= mid || r <= y){
        if(r > y || (l <= mid && a[l].v < a[r].v)){
            ansr[a[l].pos] += y-r+1;//右侧大于的
            tmp[++cnt] = a[l];
            l++;
        }else{
            ansl[a[r].pos] += lower_bound(a+x,a+mid+1,a[r])-a-x;//左侧小余的
            tmp[++cnt] = a[r];
            r++;
        }
    }
    for(int i = 1;i <= cnt;i++)
        a[x + i - 1] = tmp[i];
}

最后综合答案时利用乘法原理乘起来就是最终答案:

for(int i = 1;i <= n;i++) ans += ansl[i]*ansr[i];

CODE

#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 3e4+5;
int n;
struct Node{
    int v,pos;
    bool operator < (const Node b) const {
        return v < b.v;
    }
}a[maxn],tmp[maxn];
ll ans,ansl[maxn],ansr[maxn];
void cdq(int x,int y){
    if(x >= y) return;
    int mid = (x+y)/2;
    cdq(x,mid);cdq(mid+1,y);
    int l = x,r = mid+1,cnt = 0;
    while(l <= mid || r <= y){
        if(r > y || (l <= mid && a[l].v < a[r].v)){
            ansr[a[l].pos] += y-r+1;
            tmp[++cnt] = a[l];
            l++;
        }else{
            ansl[a[r].pos] += lower_bound(a+x,a+mid+1,a[r])-a-x;
            tmp[++cnt] = a[r];
            r++;
        }
    }
    for(int i = 1;i <= cnt;i++)
        a[x + i - 1] = tmp[i];
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    cin >> n;
    for(int i = 1;i <= n;i++) cin >> a[i].v,a[i].pos = i;
    cdq(1,n);
    for(int i = 1;i <= n;i++) ans += ansl[i]*ansr[i];
    cout << ans;
    return 0;
}