Description
有 N 个彩色糖果在平面上。小奇想在平面上取一条水平的线段,并拾起它上方或下方的所有糖果。求出最多能够拾起多少糖果,使得获得的糖果并不包含所有的颜色。
Input
包含多组测试数据,第一行输入一个正整数 T 表示测试数据组数。
接下来 T 组测试数据,对于每组测试数据,第一行输入两个正整数 N、K,分别表示点数和颜色数。
接下来 N 行,每行描述一个点,前两个数 x, y (|x|, |y| ≤ 2^30 - 1) 描述点的位置,最后一个数 z (1 ≤ z ≤ k) 描述点的颜色。
Output
对于每组数据在一行内输出一个非负整数 ans,表示答案
Sample Input
1
10 3
1 2 3
2 1 1
2 4 2
3 5 3
4 4 2
5 1 2
6 3 1
6 7 1
7 2 3
9 4 2
Sample Output
5
数据范围
对于 100% 的数据,N ≤ 100000,K ≤ 100000,T ≤ 3
题解
用树状数组维护一个区间中点的个数,
用链表维护同种颜色最左和最右的位置。
1.枚举没有取到的颜色,找出所有不包含这种颜色的区间,更新答案。
2.按照纵坐标从大到小枚举所有的点,分别在树状数组和双向链表中删除当前点,并利用这个点左右两边和它颜色相同的点之间的区间内点的个数更新答案。
对于求上面的,就将y坐标去反。
code
#include<queue>
#include<cstdio>
#include<iostream>
#include<algorithm>
#include <cstring>
#include <string.h>
#include <cmath>
#include <math.h>
#include <time.h>
#define ll long long
#define N 100003
#define M 103
#define db double
#define P putchar
#define G getchar
#define inf 998244353
using namespace std;
char ch;
void read(int &n)
{
n=0;
ch=G();
while((ch<'0' || ch>'9') && ch!='-')ch=G();
ll w=1;
if(ch=='-')w=-1,ch=G();
while('0'<=ch && ch<='9')n=(n<<3)+(n<<1)+ch-'0',ch=G();
n*=w;
}
int max(int a,int b){return a>b?a:b;}
int min(int a,int b){return a<b?a:b;}
ll abs(ll x){return x<0?-x:x;}
ll sqr(ll x){return x*x;}
void write(ll x){if(x>9) write(x/10);P(x%10+'0');}
struct node
{
int x,y,z,id;
}a[N];
bool cmpx(node a,node b){return a.x<b.x;}
bool cmpy(node a,node b){return a.y<b.y;}
int f[N],T;
int t[N],lst[N],L[N],R[N],x[N];
int n,k,ans,pos,col;
int x_(int x){return x&(-x);}
void ins(int x,int y)
{
for(int i=x;i<=n+1;i+=x_(i))
f[i]+=y;
}
int find(int x)
{
int s=0;
for(int i=x;i;i-=x_(i))
s+=f[i];
return s;
}
void updata(int l,int r)
{
if(l>r)return;
ans=max(ans,find(r)-find(l-1));
}
void work()
{
memset(lst,0,sizeof(lst));
memset(L,0,sizeof(L));
memset(R,0,sizeof(R));
memset(f,0,sizeof(f));
sort(a+1,a+1+n,cmpx);
for(int i=1;i<=n;i++)
ins(a[i].x,1);
for(int i=1;i<=n;i++)
{
pos=a[i].id;
col=a[i].z;
L[pos]=lst[col];
lst[col]=pos;
if(L[pos])R[L[pos]]=pos;
R[pos]=n+1;
updata(x[L[pos]]+1,x[pos]-1);
}
for(int i=1;i<=k;i++)
updata(x[lst[i]]+1,n+1);
sort(a+1,a+1+n,cmpy);
for(int i=1,j=1;i<=n;i++)
{
pos=a[i].id;
for(;j<=n && a[i].y==a[j].y;j++)ins(a[j].x,-1);
L[R[pos]]=L[pos];R[L[pos]]=R[pos];
updata(x[L[pos]]+1,x[R[pos]]-1);
}
}
int main()
{
for(read(T);T;T--)
{
read(n);read(k);
for(int i=1;i<=n;i++)
read(a[i].x),read(a[i].y),read(a[i].z),t[i]=a[i].x,a[i].id=i;
sort(t+1,t+1+n);
for(int i=1;i<=n;i++)
x[i]=a[i].x=lower_bound(t+1,t+1+n,a[i].x)-t;
ans=0;x[n+1]=n+1;
work();
for(int i=1;i<=n;i++)
a[i].y=-a[i].y;
work();
write(ans);
P('\n');
}
return 0;
}