CF1700F Puzzle 题解
Description
Luogu传送门
题意:
给你两个只包含
Solution
先看只有一行的情况:
我们考虑每两个相邻的点对答案的贡献,即交换的次数。
记两个数组
现在来看如果有两行如何处理:
两行比一行就多了一个上下交换的操作。
我们还是设
枚举每一位如果
当然还要加上
需要注意的是,
最后别忘了判无解:如果
Code
#include <bits/stdc++.h>
#define pb push_back
#define int long long
using namespace std;
namespace IO{
inline int read(){
int x = 0, f = 1;
char ch = getchar();
while(!isdigit(ch)) {if(ch == '-') f = -1; ch = getchar();}
while(isdigit(ch)) x = (x << 3) + (x << 1) + ch - '0', ch = getchar();
return x * f;
}
template <typename T> inline void write(T x){
if(x < 0) putchar('-'), x = -x;
if(x > 9) write(x / 10);
putchar(x % 10 + '0');
}
}
using namespace IO;
const int N = 2e5 + 10;
int n, suma, sumb;
int a[2][N], b[2][N], s[2][N];
signed main(){
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
freopen("test.out", "w", stdout);
#endif
n = read();
for(int i = 1; i <= n; ++i) suma += (a[0][i] = read());
for(int i = 1; i <= n; ++i) suma += (a[1][i] = read());
for(int i = 1; i <= n; ++i){
sumb += (b[0][i] = read());
s[0][i] = s[0][i - 1] + b[0][i];
}
for(int i = 1; i <= n; ++i){
sumb += (b[1][i] = read());
s[1][i] = s[1][i - 1] + b[1][i];
}
if(suma != sumb) return puts("-1"), 0;
int s0 = 0, s1 = 0, ans = 0;
for(int i = 1; i <= n; ++i){
s0 += a[0][i], s1 += a[1][i];
while(s0 > s[0][i] && s1 < s[1][i]) s0--, s1++, ans++;
while(s0 < s[0][i] && s1 > s[1][i]) s0++, s1--, ans++;
ans += abs(s0 - s[0][i]) + abs(s1 - s[1][i]);
}
write(ans), puts("");
}