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

· · 题解

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

题目解析

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

不难看出,对于两个金币 i 和 j (t_i < t_j),要满足 x_j - x_i ≤ t_j - t_i

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

总结一下就是

还不懂的看代码+注释

代码 + 注释

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

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

高清代码

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

完结散花,给个赞吧