cdq分治求三维偏序

这题最恶心的地方在于去重

题目链接

#include <bits/stdc++.h>
#define mid (l+r>>1)
using namespace std;
const int N=1e5+100;
struct node{
    int a,b,c,id,num;
    bool operator <(node x) const { //需要保证右区间对左区间一定没有贡献
        if(a!=x.a) return a<x.a;
        if(b!=x.b) return b<x.b;
        if(c!=x.c) return c<x.c;
    }
}s[N],tmp[N],s2[N];
int tree[2*N],f[N],tot,ans[N];
int lb(int x){
    return x&-x;
}
void add(int x,int data){
    while(x<=200000){
        tree[x] += data;
        x += lb(x);
    }
}
int que(int x){
    int ans = 0;
    while(x>0){
        ans += tree[x];
        x -= lb(x);
    }
    return ans;
}
void cdq(int l,int r) {
    if(l==r) return ;
    cdq(l,mid);
    cdq(mid+1,r);
    int i = l;
    int j = mid+1;
    int tot = l-1;                  //此时a值左区间小于等于右区间,b值在两区间内升序
    while(i <= mid&&j <= r) {       //归并的过程中维护答案
        if(s[i].b<=s[j].b) {
            tmp[++tot] = s[i];
            add(s[i].c,s[i].num);
            i++;
        }
        else {
            tmp[++tot] = s[j];
            f[s[j].id] += que(s[j].c);
            j++;
        }
    }
    while(i <= mid) {
        tmp[++tot] = s[i];
        add(s[i].c,s[i].num);
        i++;
    }
    while(j <= r){
        tmp[++tot] = s[j];
        f[s[j].id] += que(s[j].c);
        j++;
    }
    for(int i = l; i <= mid; i++) add(s[i].c,-s[i].num);    //还原树状数组
    for(int i = l; i <= r; i++) s[i] = tmp[i];              
}
int main(){
   // freopen("a.txt","r",stdin);
    ios::sync_with_stdio(0);
	int n,k;
	cin>>n>>k;
	for(int i = 1; i <= n; i++) cin>>s2[i].a>>s2[i].b>>s2[i].c;
	sort(s2+1,s2+n+1);
	tot = 0;
	for(int i = 1; i <= n; i++) {   //去重
        if(s2[i].a!=s2[i-1].a||s2[i].b!=s2[i-1].b||s2[i].c!=s2[i-1].c) {
            s[++tot] = s2[i];
            s[tot].id = tot;
            s[tot].num = 1;
        }
        else
            s[tot].num++;
	}
	cdq(1,tot);
	sort(s+1,s+tot+1);
    for(int i = 1; i <= tot; i++) {
        f[i] += s[i].num-1;     //重复元素造成的影响
        ans[f[i]]+=s[i].num;
    }
    for(int i = 0; i < n; i++) cout<<ans[i]<<endl;
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值