差分构造法推广:arc166_d

本文搬运自本人高中时期CSDN博客,若图片加载不出来,可到原文查看:https://blog.csdn.net/zhangtingxiqwq/article/details/133694378

https://atcoder.jp/contests/arc166/tasks/arc166_d

首先肯定是这样子放:

在这里插入图片描述

考虑相邻之间的差,本质就是橙色区间减蓝色区间数量

区间数量越少显然越优,所以我们要么保留橙区间,要么保留紫区间,然后两两匹配

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read(){int x=0,f=1;char ch=getchar(); while(ch<'0'||
ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){
x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}return x*f;}
#define Z(x) (x)*(x)
#define pb push_back
//mt19937 rand(time(0));
//mt19937_64 rand(time(0));
//srand(time(0));
#define N 400010
//#define M
//#define mo
struct node {
int op, x, y;
}a[N], t;
queue<node>q;
int n, m, i, j, k, T, ans;
int x[N], y[N], d;

bool cmp(node x, node y) {
if(x.x==y.x) return x.op<y.op;
return x.x<y.x;
}

signed main()
{
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
// T=read();
// while(T--) {
//
// }
n=read(); x[0]=-1e12; x[n+1]=1e12; ans=1e12;
for(i=1; i<=n; ++i) x[i]=read();
for(i=1; i<=n; ++i) y[i]=read();
for(i=1; i<=n+1; ++i) {
d=y[i]-y[i-1];
if(d>0) a[++k].x=x[i-1]+1, a[k].y=d, a[k].op=1;
if(d<0) a[++k].x=x[i]-1, a[k].y=-d, a[k].op=2;
}
sort(a+1, a+k+1, cmp);
for(i=1; i<=n; ++i) {
// printf("%lld : %lld %lld\n", a[i].op, a[i].x, a[i].y);
if(a[i].op==1) q.push(a[i]);
else {
while(!q.empty() && q.front().y<=a[i].y) {
t=q.front(); q.pop();
ans=min(ans, a[i].x-t.x); a[i].y-=t.y;
}
if(a[i].y) {
t=q.front(); q.front().y-=a[i].y;
ans=min(ans, a[i].x-t.x);
}
}
}
if(ans>1e9) printf("-1");
else printf("%lld", ans);
return 0;
}