本题解不同于其他题解,码量较大,但是个人感觉比较自然,下面是模拟赛思路与代码。
我们先分析题目,注意到出租车从 出发最终到 ,无论怎么绕路,至少需要走 的距离。所以我们令基础路程为 。
然后观察运输任务,若 (前向牛),出租车必须向右穿过该区间;若 (后向牛),出租车必须向左穿过该区间。
前向牛需要向右走,后向牛需要向左走。所以我们考虑尽量复用这部分。
我们将数轴按所有出现过的 离散化为若干个不重合的区间。
对于任意一个长度为 的段 ,设: 为覆盖该段的前向牛数量(即需要向右穿过该段的牛数)。 为覆盖该段的后向牛数量(即需要向左穿过该段的牛数)。
设出租车在这个段上向右穿过的次数为 ,向左穿过的次数为 。
- 出租车从 出发到 ,我们最终一定需要到终点 。因此对于数轴上任意一段,向右穿过的次数必须比向左穿过的次数多 1,即 。
- 为了满足前向牛,必须有 ;为了满足后向牛,必须有 。
- 出租车在这个段上行驶的总路程为 。由于 ,总路程为 。要使总路程最小,即最小化 。
- 由上面的约束知 且 (由 )。 因此,。
- 计算额外路程:基础路程 已经包含了每个段向右走 1 次的距离(即 )。所以该段的额外路程为: 注:若 ,则 ,由于 ,公式依然成立,等价于 。
时间复杂度 ,空间复杂度 。
具体实现见代码。
这是经过修缮的赛时代码
代码
#include <bits/stdc++.h>
#define debug(x) cerr << #x << " = " << x << endl
#define ui unsigned int
#define ull unsigned long long
#define ll long long
#define lbt(i) (i & -i)
using namespace std;
const ui maxn = 1e5 + 10;
struct Taxi {
ll begin, end;
} f[maxn], b[maxn]; // f: 前向牛(a_i < b_i) b: 后向牛(a_i > b_i)
struct Node {
ll l, r;
} st[maxn << 1];
ll n, cnt_st;
// 树状数组,bit_f 记录前向牛覆盖数,bit_b 记录后向牛覆盖数
ll bit_f[maxn << 1], bit_b[maxn << 1];
void BitAdd(ll bit[], int i, ll x) {
while (i <= cnt_st) {
bit[i] += x;
i += lbt(i);
}
}
ll BitQuery(ll bit[], int i) {
ll ans = 0;
while (i) {
ans += bit[i];
i -= lbt(i);
}
return ans;
}
// 二分查找函数:将坐标 x 映射到离散化后的线段编号
// op = 1: 找左端点匹配 (用于确定区间的起始段)
// op = 0: 找右端点匹配 (用于确定区间的结束段)
ll tf(ll x, bool op) {
int l = 1, r = cnt_st;
if (op) {
while (l <= r && r > 0) {
int mid = (l + r) >> 1;
if (st[mid].l < x) {
l = mid + 1;
} else if (st[mid].l > x) {
r = mid - 1;
} else {
return mid;
}
}
return l;
} else {
while (l <= r) {
int mid = (l + r) >> 1;
if (st[mid].r < x) {
l = mid + 1;
} else if (st[mid].r > x) {
r = mid - 1;
} else {
return mid;
}
}
return l;
}
}
ll a[maxn << 1];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
ll ans = 0, m, cnt_f = 0, cnt_b = 0;
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
cin >> a[i] >> a[i + n];
if (a[i] < a[i + n]) {
f[++cnt_f].begin = a[i];
f[cnt_f].end = a[i + n];
} else {
b[++cnt_b].begin = a[i];
b[cnt_b].end = a[i + n];
}
}
sort(a + 1, a + (n << 1) + 1);
for (int i = 1; i <= n << 1; ++i) {
if (st[cnt_st].r != a[i]) {
st[++cnt_st].l = a[i - 1];
st[cnt_st].r = a[i];
}
}
if (st[cnt_st].r != m) {
st[++cnt_st].l = a[n << 1];
st[cnt_st].r = m;
}
for (int i = 1; i <= cnt_f; ++i) {
ll L = tf(f[i].begin, 1);
ll R = tf(f[i].end, 0);
BitAdd(bit_f, L, 1);
BitAdd(bit_f, R + 1, -1);
}
// 后向牛方向是 begin -> end (其中 begin > end)
// 等价于需要在 [end, begin] 区间向左穿过,所以 L 找 end,R 找 begin
for (int i = 1; i <= cnt_b; ++i) {
ll L = tf(b[i].end, 1);
ll R = tf(b[i].begin, 0);
BitAdd(bit_b, L, 1);
BitAdd(bit_b, R + 1, -1);
}
ans = m;
for (int i = 1 ; i <= cnt_st; ++i) {
ll sum_f = BitQuery(bit_f, i), sum_b = BitQuery(bit_b, i);
if (sum_b < sum_f) {
ans += (st[i].r - st[i].l) * (sum_f - 1) * 2ll;
} else {
ans += (st[i].r - st[i].l) * sum_b * 2ll;
}
}
cout << ans;
}