LIS2 - Another Longest Increasing Subsequence Problem
no tags
Given a sequence of N pairs of integers, find the length of the longest increasing subsequence of it.
An increasing sequence A1..An is a sequence such that for every i < j, Ai < Aj.
A subsequence of a sequence is a sequence that appears in the same relative order, but not necessarily contiguous.
A pair of integers (x1, y1) is less than (x2, y2) iff x1 < x2 and y1 < y2.
Input
The first line of input contains an integer N (2 ≤ N ≤ 100000).
The following N lines consist of N pairs of integers (xi, yi) (-109 ≤ xi, yi ≤ 109).
Output
The output contains an integer: the length of the longest increasing subsequence of the given sequence.
Example
Input: 8 1 3 3 2 1 1 4 5 6 3 9 9 8 7 7 6 Output: 3
题意:求最长上升子序列,不过换成二元组的形式。
思路:实质上这是一个三维偏序,还有一维是原数对的前后顺序。考虑CDQ分治,以前CDQ分治是先递归左区间再递归右区间,但是本题右区间的值是高度依赖左区间的,比如这组数(1,1),(2,2),(3,3),(4,4),以前的CDQ分治对于(4,4)只能从前两个转移过来造成结果输出3。也就是说,当递归完左区间后要立刻更新右区间的答案,再递归右区间,就不会出错了。最后这题用树状数组的话要离散化y值。
# include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5+30;
struct node{
int x, y, ans;
}a[maxn], tmp[maxn];
int b[maxn], cnt, imax[maxn], id[maxn];
void update(int pos, int val){
for(;pos<=cnt; pos+=pos&-pos){
if(imax[pos] < val) imax[pos] = val;
else break;
}
}
int cal(int pos){
int res = 0;
for(;pos>0; pos-=pos&-pos)
res = max(res, imax[pos]);
return res;
}
void clr(int pos){
for(;pos<=cnt; pos+=pos&-pos){
if(imax[pos] == 0) break;
imax[pos] = 0;
}
}
bool cmp(int i, int j){
return a[i].x < a[j].x;
}
void cdq(int l, int r){
if(l == r) return;
int mid = l+r>>1, L=l, R, k=0;
cdq(l, mid);
for(int i=mid+1; i<=r; ++i) id[i] = i;//准备更新右区间答案
sort(id+mid+1, id+r+1, cmp);
for(int i=mid+1; i<=r; ++i){
int c = id[i];
while(L<=mid && a[L].x < a[c].x){
update(a[L].y, a[L].ans);++L;
}
a[c].ans = max(a[c].ans, cal(a[c].y-1)+1);
}
for(int i=l; i<=mid; ++i) clr(a[i].y);//清空BIT
cdq(mid+1, r);
L=l, R=mid+1;//准备归并本区间
while(L<=mid && R<=r){
if(a[L].x <= a[R].x) tmp[k++] = a[L++];
else tmp[k++] = a[R++];
}
while(L<=mid) tmp[k++] = a[L++];
while(R<=r) tmp[k++] = a[R++];
for(int i=0; i<k; ++i) a[l+i] = tmp[i];
}
int main(){
int n; cnt = 0;
scanf("%d",&n);
for(int i=1; i<=n; ++i){
scanf("%d%d",&a[i].x,&a[i].y);
a[i].ans = 1;
b[++cnt] = a[i].y;
}
sort(b+1, b+1+cnt);
cnt = unique(b+1, b+1+cnt)-b-1;
for(int i=1; i<=n; ++i) a[i].y = lower_bound(b+1, b+1+cnt, a[i].y)-b;
cdq(1, n);
int ans = 0;
for(int i=1; i<=n; ++i) ans = max(ans, a[i].ans);
printf("%d\n",ans);
return 0;
}