题解:P17545 [JAG 2026 Summer Camp #2] Robot Damage
思路
真正的碰撞不能直接等同于到达墙面,因为题目排除了恰好到墙和原地推墙两种情况。先处理这个细节:对正位移
把每个时刻的接触条件变成阈值
记拆分后、完全没有墙时的前缀位置为
找最近的一个
令
左墙只需把所有
墙间距离较小时,只需前两个周期
设一个周期内
于是这一类查询的答案为
墙间距离较大时,跳过中间的自由移动
如果
从任意起点
为了跳过大量周期,可以先将净位移为负的整个序列取反,之后统一令
接下来若还有周期,就模拟第一次触及右墙的周期。它的终点固定为 long long 累加;单次乘积上界为
复杂度分析
每个测试的拆分序列长度为
参考代码
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
struct Counter {
vector<ll> plus, minus;
void add(ll x, bool positive) {
(positive ? plus : minus).push_back(x);
}
void build() {
sort(plus.begin(), plus.end());
sort(minus.begin(), minus.end());
}
ll count(ll x) const {
return (plus.end() - lower_bound(plus.begin(), plus.end(), x))
- (minus.end() - lower_bound(minus.begin(), minus.end(), x));
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tests;
cin >> tests;
while (tests--) {
int n;
cin >> n;
vector<ll> v(n);
ll delta = 0;
for (ll &x : v) { cin >> x; delta += x; }
if (delta < 0) {
delta = -delta;
for (ll &x : v) x = -x;
}
int len = 2 * n;
vector<ll> s(2 * len + 1);
for (int j = 0; j < 2 * len; ++j) {
ll x = v[j / 2 % n], sign = x > 0 ? 1 : -1;
s[j + 1] = s[j] + (j % 2 == 0 ? x - sign : sign);
}
ll low = *min_element(s.begin(), s.begin() + len + 1);
ll high = *max_element(s.begin(), s.begin() + len + 1);
Counter narrow[2], single[2];
for (int side = 0; side < 2; ++side) {
vector<pair<ll, ll>> st;
ll pref = LLONG_MIN;
for (int j = 0; j < 2 * len; ++j) {
ll cur = side == 0 ? s[j] : -s[j], mn = cur;
while (!st.empty() && st.back().first <= cur) {
mn = min(mn, st.back().second);
st.pop_back();
}
ll alpha = (cur - mn) / 2;
if (st.empty()) alpha = max(alpha, cur);
st.push_back({cur, mn});
pref = max(pref, cur);
if ((v[j / 2 % n] > 0) == (side == 0)) {
narrow[j / len].add(alpha, j % 2 == 1);
if (j < len && cur == pref) single[side].add(cur, j % 2 == 1);
}
}
}
for (auto &c : narrow) c.build();
for (auto &c : single) c.build();
int q;
cin >> q;
while (q--) {
ll w, times;
cin >> w >> times;
if (2 * w <= high - low) {
cout << narrow[0].count(w) + (times - 1) * narrow[1].count(w) << '\n';
continue;
}
// 宽区间内一周期最多碰到一侧墙;返回终点和伤害。
auto run = [&](ll x) -> pair<ll, ll> {
if (x + high >= w) return {w - high + delta, single[0].count(w - x)};
if (x + low <= -w) return {-w - low + delta, single[1].count(w + x)};
return {x + delta, 0};
};
auto [x, ans] = run(0);
--times;
if (times && delta > 0) {
ll bound = w - high;
if (x < bound) {
ll skip = min(times, (bound - x + delta - 1) / delta);
x += skip * delta;
times -= skip;
}
if (times) {
auto [y, damage] = run(x);
ans += damage;
--times;
ans += times * run(y).second;
}
}
cout << ans << '\n';
}
}
}