类似题目:[ARC073D] Many Moves
考虑特殊性质 B:
从暴力开始考虑,可以想到进行 dp。显然需要先按时间排序,然后设 表示考虑到第 个操作,当前一只手在 ,另一只手在 的答案。可以很容易地列出方程:
注意第二个方程,因为状态设计,所以需要将下标存储的手改变。这样做是 的。
第一个方程显然是全局加,考虑线段树优化。尝试用同样的方法优化第二个方程。
将 拆开:
将第二个 dp 方程重写:
这样就很能看出来优化了,线段树存储 和 ,支持区间查询最小值即可。按照上面的方法计算即可得出答案。
再考虑没有特殊性质 B:
这时候如果两个操作满足 ,就不能使用第一种转移了。一种简单的方法是直接将其他位置 即可。注意不要溢出。
#include <iostream>
#include <cstdio>
#include <algorithm>
#define ll long long
#define N 300005
#define INF (ll)1e12
#define PII pair<ll, ll>
#define lowbit(x) x&(-x)
using namespace std;
inline ll rd(){
ll res=0, f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=getchar();}
while(ch>='0'&&ch<='9') res=(res<<3)+(res<<1)+(ch^48), ch=getchar();
return (f>0?res:-res);
}
ll c, n, m, s, t;
struct Data{
ll x, y;
}q[N];
struct Node{
ll l, r, val1, val2, tag;
};
struct Tree{
Node t[N<<2];
void pushup(ll p){
t[p].val1=min(t[p<<1].val1, t[p<<1|1].val1);
t[p].val2=min(t[p<<1].val2, t[p<<1|1].val2);
}
void pushdown(ll p){
if(!t[p].tag) return;
t[p<<1].val1+=t[p].tag, t[p<<1|1].val1+=t[p].tag;
t[p<<1].val2+=t[p].tag, t[p<<1|1].val2+=t[p].tag;
t[p<<1].tag+=t[p].tag, t[p<<1|1].tag+=t[p].tag;
t[p].tag=0;
}
void build(ll p, ll l, ll r){
t[p].l=l, t[p].r=r, t[p].val1=t[p].val2=INF;
if(l==r) return;
ll mid=(l+r)>>1;
build(p<<1, l, mid);
build(p<<1|1, mid+1, r);
pushup(p);
}
void update(ll p, ll nl, ll nr, ll k){
ll l=t[p].l, r=t[p].r;
if(nl<=l&&nr>=r) return t[p].val1+=k, t[p].val2+=k, t[p].tag+=k, void();
ll mid=(l+r)>>1; pushdown(p);
if(nl<=mid) update(p<<1, nl, nr, k);
if(nr>mid) update(p<<1|1, nl, nr, k);
pushup(p);
}
void change(ll p, ll np, ll k){
ll l=t[p].l, r=t[p].r;
if(l==r) return t[p].val1=min(t[p].val1, k-l), t[p].val2=min(t[p].val2, k+l), void();
ll mid=(l+r)>>1; pushdown(p);
if(np<=mid) change(p<<1, np, k);
else change(p<<1|1, np, k);
pushup(p);
}
PII qrymin(ll p, ll nl, ll nr){
ll l=t[p].l, r=t[p].r;
if(nl<=l&&nr>=r) return {t[p].val1, t[p].val2};
ll mid=(l+r)>>1; pushdown(p);
PII res1={INF, INF}, res2={INF, INF};
if(nl<=mid) res1=qrymin(p<<1, nl, nr);
if(nr>mid) res2=qrymin(p<<1|1, nl, nr);
return {min(res1.first, res2.first), min(res1.second, res2.second)};
}
ll qryans(ll p){
ll l=t[p].l, r=t[p].r;
if(l==r) return t[p].val1+l;
pushdown(p);
return min(qryans(p<<1), qryans(p<<1|1));
}
}T;
int main(){
c=rd(), n=rd(), m=rd(), s=1, t=n;
T.build(1, 1, n), T.change(1, t, 0);
for(int i=1; i<=m; i++) q[i]={rd(), rd()};
sort(q+1, q+m+1, [](Data x, Data y){return x.x<y.x;});
for(int i=1; i<=m; i++){
ll t=q[i].y;
ll num1=min(T.qrymin(1, 1, t).first+t, T.qrymin(1, 1, t).second+n-t);
ll num2=min(T.qrymin(1, t+1, n).second-t, T.qrymin(1, t+1, n).first+n+t);
ll num=min(num1, num2);
if(q[i].x==q[i-1].x) T.update(1, 1, n, INF);
else T.update(1, 1, n, min(abs(t-s), n-abs(t-s)));
T.change(1, s, num);
s=t;
}
printf("%lld\n", T.qryans(1));
return 0;
}