题解:P14078 [GESP202509 七级] 金币收集
题解:P14078 [GESP202509 七级] 金币收集
题目解析
小
不难看出,对于两个金币
等价于
总结一下就是
- 先给数组按时间
t 或坐标x 排个序,我按的坐标x - 过滤掉不可能收集的金币
(x > t) - 对剩余金币记录
val = t - x - 求
val 的最长非递减子序列(LIS) 时间复杂度
- 排序:显然
O(n log n) - LIS + 二分优化:
O(n log n) - 总时间复杂度不过
O(n log n) 显然可做
还不懂的看代码+注释
代码 + 注释
后有高清代码,适合另一部分人观看
#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;
}
完结散花,给个赞吧