【模板】三维偏序

题面

题解

这是一个三维偏序模板
我用的是CDQ分治
推荐CDQ分治入门Blog
推荐CDQ分治提高Blog

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include<bits/stdc++.h>
#define RG register
#define clear(x, y) memset(x, y, sizeof(x));
using namespace std;

inline int read()
{
int data=0, w=1;
char ch=getchar();
while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
if(ch=='-') w=-1, ch=getchar();
while(ch>='0'&&ch<='9') data=(data<<3)+(data<<1)+(ch^48), ch=getchar();
return data*w;
}

const int maxn(100010);
struct node
{
int a, b, c, mult, ans;
inline void read() { a=::read(); b=::read(); c=::read(); }
}a[maxn], v[maxn];

inline bool cmpx(const node &a, const node &b) { return (a.a<b.a)||(a.a==b.a&&a.b<b.b)||(a.a==b.a&&a.b==b.b&&a.c<b.c); }
inline bool cmpy(const node &a, const node &b) { return (a.b<b.b)||(a.b==b.b&&a.c<b.c); }

int n, ans[maxn], k, m, c[maxn << 1], mul;
inline int lowbit(int x) { return x&(-x); }
inline void update(int pos, int val) { while(pos<=k) c[pos]+=val, pos+=lowbit(pos); }
inline int query(int pos) { int tot=0; while(pos) tot+=c[pos], pos-=lowbit(pos); return tot; }

void CDQ(int l, int r)
{
if(l==r) return;
int mid(l+r>>1);
CDQ(l, mid); CDQ(mid+1, r);
int j=l;
for(RG int i=mid+1;i<=r;i++)
{
while(a[j].b<=a[i].b && j<=mid) update(a[j].c, a[j].mult), j++;
a[i].ans+=query(a[i].c);
}
for(RG int i=l;i<j;i++) update(a[i].c, -a[i].mult);
inplace_merge(a+l, a+mid+1, a+r+1, cmpy);
}

int main()
{
m=read(); k=read();
for(RG int i=1;i<=m;i++) v[i].read();
sort(v+1, v+m+1, cmpx);
for(RG int i=1;i<=m;i++)
{
mul++;
if((v[i].a^v[i+1].a) || (v[i].b^v[i+1].b) || (v[i].c^v[i+1].c)) a[++n]=v[i], a[n].mult=mul, mul=0;
}
CDQ(1, n);
for(RG int i=1;i<=n;i++) ans[a[i].ans+a[i].mult-1]+=a[i].mult;
for(RG int i=0;i<m;i++) printf("%d\n", ans[i]);
return 0;
}

我们学过的实际上就是CDQ分治的算法

归并排序求逆序对

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×