跳到正文

题解

题解:P14078 [GESP202509 七级] 金币收集

DomiSun约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年10月6日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 5 分钟
获赞
1
题目
P14078

版本

  1. v2当前
  2. v1

题解:P14078 [GESP202509 七级] 金币收集

题目解析

小 AA 需要在数轴上收集金币,但只能向右移动或保持不动。每个金币在特定时刻出现在特定位置,要收集金币必须在那个时刻恰好到达那个位置。 不难看出,小 AA 只能一步一步向右走,所用 tt 时刻,最远能到走 tt 个单位 ,收集金币必须满足时间顺序,从金币 ii 到金币 jj ,必须满足 xj−xi≤tj−tix_j - x_i \le t_j - t_i , 我们完全可以把这个收集金币问题转化成,受约束的的最长金币序列问题。

不难看出,对于两个金币 ii 和 jj (ti<tj)(t_i < t_j),要满足 xj−xi≤tj−tix_j - x_i ≤ t_j - t_i

等价于 tj−xj≥ti−xit_j - x_j ≥ t_i - x_i 即 t−xt - x 的值是非递减的,也就是说我们可以靠这个性质来转化成求最长非递减子序列。

总结一下就是

  • 先给数组按时间 tt 或坐标 xx 排个序,我按的坐标 xx
  • 过滤掉不可能收集的金币 (x>t)(x > t)
  • 对剩余金币记录 val=t−xval = t - x
  • 求 valval 的最长非递减子序列 (LIS)(LIS)

时间复杂度

  • 排序:显然 O(nlogn)O(n log n)
  • LIS + 二分优化:O(nlogn)O(n log n)
  • 总时间复杂度不过 O(nlogn)O(n log n) 显然可做

还不懂的看代码+注释

代码 + 注释

后有高清代码,适合另一部分人观看

C++
#include <bits/stdc++.h>
using namespace std;
#define int long long  
const int N = 1e5 + 10;
int n,f[N]; // f存储最长非递减子序列
struct node{
    int x,t;  // x: 金币坐标, t: 金币出现时刻
}a[N];
// 比较函数:按坐标x排序,坐标相同按时间t排序
bool cmp(node x, node y){
    if(x.x == y.x) return x.t < y.t;
    else return x.x < y.x;
}
signed main(){
    cin >> n;
    for(int i = 1;i <= n;i++) cin >> a[i].x >> a[i].t;
    sort(a+1,a+n+1,cmp);
    int l = 0;  // 记录当前最长序列长度
    for(int i = 1;i <= n;i++){
        // 检查是否能到达该金币位置
        // 因为从时刻0坐标0开始,最多移动t_i步,所以x_i必须≤t_i
        if(a[i].x > a[i].t) continue; //不满足,过滤掉
        // 核心思想:计算 t-x 的值
        // 对于两个金币i和j(t_i<t_j),要满足移动约束:x_j - x_i ≤ t_j - t_i
        // 这等价于:t_j - x_j ≥ t_i - x_i
        // 所以我们要维护 t-x 的非递减序列
        int val = a[i].t - a[i].x;
        // 如果当前值大于等于序列末尾值,直接加入序列
        if(val >= f[l]) f[++l] = val;
        else{
            // 否则找到第一个大于val的位置进行替换
            // 使用upper_bound因为允许相等(非严格递增)
            int pos = upper_bound(f+1,f+l+1,val)-f;
            f[pos] = val;
        }
    }
    cout << l;  // 输出答案
    return 0;
}

高清代码

C++
#include <bits/stdc++.h>
using namespace std;
#define int long long  
const int N = 1e5 + 10;
int n,f[N]; 
struct node{int x,t;}a[N];
bool cmp(node x, node y){
    if(x.x == y.x) return x.t < y.t;
    else return x.x < y.x;
}
signed main(){
    cin >> n;
    for (int i = 1;i <= n;i++) cin >> a[i].x >> a[i].t;
    sort(a + 1, a + n + 1, cmp);
    int l = 0;  
    for(int i = 1;i <= n;i++){
        if(a[i].x > a[i].t) continue; 
        int val = a[i].t - a[i].x;
        if(val >= f[l]) f[++l] = val;
        else{
            int pos = upper_bound(f+1,f+l+1,val) - f;
            f[pos] = val;
        }
    }
    cout << l;  
    return 0;
}

完结散花,给个赞吧

原文