题解:P14078 [GESP202509 七级] 金币收集
题目分析
小 需要在数轴上收集金币,但只能向右移动或保持不动。每个金币在特定时刻出现在特定位置,要收集金币必须在那个时刻恰好到达那个位置。
约束条件
- 移动约束 : 不难看出,小 只能一步一步向右走,所用 时刻,最远能到走 个单位
- 时间约束 :收集金币必须满足时间顺序
- 收集约束 :从金币 到金币 ,必须满足 显然由移动约束所得
算法思路
我们完全可以把这个收集金币问题转化成,满足约束条件的最长金币序列问题。
不难看出,对于两个金币 和 ,要满足
等价于 即 的值是非递减的
总结一下就是
- 先给数组按时间 或坐标 排个序,我按的坐标
- 过滤掉不可能收集的金币
- 对剩余金币记录
- 求 的最长非递减子序列
分析时间复杂度
- 排序:显然
- LIS + 二分优化:
- 总时间复杂度不过 显然可做
还不懂的看代码+注释
代码 + 注释
后有高清代码,适合另一部分人观看
#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;
}完结散花,给个赞吧,管理员题解给过吧,花了不少时间