CDQ分治[陌上花开 ]

关于CDQ,是大神陈丹琦写出来的算法,具体的看这个连接

https://www.cnblogs.com/lck-lck/p/9657753.html

https://blog.csdn.net/wu_tongtong/article/details/78785836

Description

有n朵花,每朵花有三个属性:花形(s)、颜色(c)、气味(m),用三个整数表示。

现在要对每朵花评级,一朵花的级别是它拥有的美丽能超过的花的数量。

定义一朵花A比另一朵花B要美丽,当且仅Sa>=Sb,Ca>=Cb,Ma>=Mb。

显然,两朵花可能有同样的属性。需要统计出评出每个等级的花的数量。

Input

第一行为N,K (1 <= N <= 100,000, 1 <= K <= 200,000 ), 分别表示花的数量和最大属性值。

以下N行,每行三个整数si, ci, mi (1 <= si, ci, mi <= K),表示第i朵花的属性

Output

包含N行,分别表示评级为0...N-1的每级花的数量。

Sample Input

10 3
3 3 3
2 3 3
2 3 1
3 1 1
3 1 2
1 3 1
1 1 2
1 2 2
1 3 2
1 2 1

Sample Output

3
1
3
0
1
0
1
0
0
1

Hint

Source黑暗爆炸3262

好的那么这就是个三维的偏序问题,要注意一下会有重复的(属性相同的花),要去重,然后自己不能比自己更美丽,这个三维的要用树状数组搞一下,当然线段树也可以,但是时间常数太大,然后每次的sort是nlogn的有点慢,可以用拆分的优化成n

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=1e5+5;
typedef long long ll;
struct node{
	int x,y,z,ans,nub;//三个维度在这道题里面就是花的三个性质,ans表示该花优于多少朵花,nub表示和这个花相同属性的花有多少朵 
}a[maxn];
int siz,hight,treearray[maxn<<2],cnt,ans[maxn];//tree树状数组,cnt是去重之后的元素个数 
inline int cmp2(struct node a,struct node b){
	if(a.y!=b.y)
	    return a.y<b.y;
	else
	    return a.z<b.z;
}
inline int cmp1(struct node a,struct node b){
	if(a.x!=b.x)
	    return a.x<b.x;
	else 
	    return cmp2(a,b);
}
inline void add(int locate,int nub){//树状数组 
	while(locate<=hight){
		treearray[locate]+=nub;
		locate+=locate&(-locate);
	}
	return;
}
inline int quary(int locate){//树状数组 
	int ans=0;
	while(locate>0){
		ans+=treearray[locate];
		locate-=locate&(-locate);
	}
	return ans;
}
void cdq(int l,int r){
	if(l==r)
        return ;
	int mid=(l+r)>>1;
	cdq(l,mid);
	cdq(mid+1,r);
	sort(a+l,a+mid+1,cmp2);//按照y,z的顺序排序 
	sort(a+mid+1,a+r+1,cmp2);
	int pl=l,pr=mid+1;
	for(;pr<=r;pr++){
		while(pl<=mid&&a[pl].y<=a[pr].y){//若第二维的左子区间的a[pl].y对右子区间产生了贡献
			add(a[pl].z,a[pl].nub);//就把第三维的a[pl].z扔进树状数组,这里左子区间的元素最多会被仍进去一次 
			pl++;
		}
		a[pr].ans+=quary(a[pr].z);
	} 
	for(int i=l;i<=mid&&a[i].y<=a[r].y;i++)//这里每次结束的时候或者在cdq开始的时候要清空树状数组,但是如果用memset会超时,所以这里对于每个被扔进去的在把他减掉 
	    add(a[i].z,-a[i].nub);
	return;
}
int main(){
	scanf("%d%d",&siz,&hight);
	for(int i=1;i<=siz;i++){
		scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].z);
	}
	sort(a+1,a+siz+1,cmp1);//先按照x,y,z的优先去排序,消除x的影响 
	for(int i=1;i<=siz;i++){
		if(a[i].x!=a[cnt].x||a[i].y!=a[cnt].y||a[i].z!=a[cnt].z)//去重 
		    a[++cnt]=a[i];
		a[cnt].nub++;
	}
	cdq(1,cnt);//CDQ分治 
	for(int i=1;i<=cnt;i++){
		ans[a[i].ans+a[i].nub-1]+=a[i].nub;//把去重的过程还原回来并计算ans数组 
	}
	for(int i=0;i<siz;i++){
		printf("%d\n",ans[i]);
	}
    return 0;
}

2021.9.22

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值