题意
这题第一眼很像我前几天做的 P3076,但是该题是一次只能载一个乘客,而本题是可以同时载多个。
有一条数轴,需要从 走到 ,且路程必须包含 (),求最短路程。
分析
正确代码
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define INF 1e18
struct node {
int s, t;
bool operator<(node x)const { return s < x.s; }
};
int n, m, n1;
node a[300005];
signed main() {
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin >> n >> m;
for(int i = 1, s, t; i <= n; ++ i) {
cin >> s >> t;
if(s > t) // 负方向才存!
a[++ n1] = {t, s};
}
sort(a + 1, a + n1 + 1);
int nows = a[1].s, nowt = a[1].t, ans = m; // nows,nowt 当前区间的始末
for(int i = 2; i <= n; ++ i){
if(a[i].s <= nowt) // 与当前区间重叠
nowt = max(nowt, a[i].t); // 延展区间
else
ans += 2 * (nowt - nows), nows = a[i].s, nowt = a[i].t; // 结算该区间答案,并更新区间位置
}
ans += 2 * (nowt - nows); // 别忘了!
cout << ans;
return 0;
}