跳到正文

题解

P5939 [POI 1998 R3] 折线

ImmatureDreamer约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年5月10日
更新
2026年5月10日
篇幅
约 2 分钟
题目
P5939

版本

  1. v1当前

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

{yA+xA≤yB+xByA−xA≥yB−xB\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)(y+x,y-x) 存储。然后按第一维升序、第二维降序排序,问题就变成了原序列至少需要拆成多少个单调不上升序列。

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

C++
#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;
}

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

原文