CDQ分治模板题
#include<cstdio>
#include<cctype>
#include<algorithm>
#include<cstring>
using namespace std;
inline int read()
{
int x = 0, flag = 1;
char c;
while(! isgraph(c = getchar()))
if(c == '-')
flag *= - 1;
while(isgraph(c))
x = x * 10 + c - '0', c = getchar();
return x * flag;
}
void println(int x)
{
if(x < 0)
putchar('-');
if(x == 0)
putchar('0');
int ans[10 + (1 << 4)], top = 0;
while(x)
ans[top ++] = x % 10, x /= 10;
for(; top; top --)
putchar(ans[top - 1] + '0');
putchar('
');
}
const int MAXN = (int)1e5 + (1 << 5);
struct node
{
int x, y, z, ID;
node(int x = 0, int y = 0, int z = 0, int ID = 0): x(x), y(y), z(z), ID(ID){}
}a[MAXN], b[MAXN];
int operator <(node x, node y)
{
if(x.x != y.x)
return x.x < y.x;
if(x.y != y.y)
return x.y < y.y;
return x.z <= y.z;
}
int ans[MAXN];
int cmp(node x, node y)
{
if(x.y != y.y)
return x.y < y.y;
return x.ID < y.ID;
}
int tree[MAXN];
int MAXZ;
void modify(int u, int delta)
{
while(u <= MAXZ)
tree[u] += delta, u += (u & (-u));
}
int query(int u)
{
int ret = 0;
while(u)
ret += tree[u], u -= (u & (- u));
return ret;
}
void CDQ(int L, int R)
{
if(L == R)
return;
int mid = (L + R) >> 1;
int top = 0;
for(int i = L; i <= mid; i ++)
b[top ++] = node(0, a[i].y, a[i].z, 0);
for(int i = mid + 1; i <= R; i ++)
b[top ++] = node(0, a[i].y, a[i].z, a[i].ID);
sort(b, b + top, cmp);
for(int i = 0; i < top; i ++)
{
if(b[i].ID == 0)
modify(b[i].z, 1);
else
ans[b[i].ID] += query(b[i].z);
}
for(int i = 0; i < top; i ++)
if(b[i].ID == 0)
modify(b[i].z, - 1);
CDQ(L, mid);
CDQ(mid + 1, R);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("HDU5618.in", "r", stdin);
freopen("HDU5618.out", "w", stdout);
#endif
int T = read();
while(T --)
{
int n = read();
for(int i = 1; i <= n; i ++)
{
int x = read(), y = read(), z = read();
a[i] = node(x, y, z, i);
MAXZ = max(MAXZ, a[i].z);
}
sort(a + 1, a + n + 1);
memset(ans, 0, sizeof(ans));
memset(tree, 0, sizeof(tree));
int cnt = 0;
for(int i = n; i; i --)
{
if((a[i].x == a[i + 1].x)
&& (a[i].y == a[i + 1].y)
&& (a[i].z == a[i + 1].z))
cnt ++;
else
cnt = 0;
ans[a[i].ID] += cnt;
}
CDQ(1, n);
for(int i = 1; i <= n; i ++)
println(ans[i]);
}
}