P5939 [POI 1998 R3] 折线

· · 题解

将折线每一段与 x 轴的角度关系转化为端点坐标的关系。根据初中数学,端点坐标为 (x_A,y_A)、(x_B,y_B) 的线段与 x 轴夹角在 [-45^\circ,45^\circ] 可以转化为 -1 \leq \frac{y_B-y_A}{x_B-x_A} \leq 1(即斜率),即

\left\{ \begin{matrix} y_A+x_A \leq y_B+x_B \\ y_A-x_A \geq y_B-x_B \end{matrix} \right.

这启发我们将每个点按 (y+x,y-x) 存储。然后按第一维升序、第二维降序排序,问题就变成了原序列至少需要拆成多少个单调不上升序列。

根据 Dilworth 定理,该问题等价于求原序列的最长上升子序列长度。

#include<bits/stdc++.h>
using namespace std;
using LL = long long int;
const int N = 30005;
int n, cnt, d[N];
struct point{
    int x, y;
    bool operator<(const point& o)const{return x == o.x? y > o.y: x < o.x;} // 重载运算符,定义 cmp 函数也是可以的。
}p[N];
int main(){
    scanf("%d", &n);
    for(int i = 1, x, y; i <= n; ++ i) cin >> x >> y, p[i] = {y + x, y - x};
    sort(p + 1, p + n + 1);
    for(int i = 1; i <= n; ++ i) d[cnt && p[i].y <= d[cnt]? lower_bound(d + 1, d + cnt + 1, p[i].y) - d: ++ cnt] = p[i].y; // lower_bound 是二分查找有序序列第一个大于等于某数的位置
    // 使用队列法维护最长上升子序列
    printf("%d", cnt);
    return 0;
}

不要为明天而烦恼,因为明天自有明天的烦恼。