CF1700F Puzzle 题解

· · 题解

Description

Luogu传送门

题意:

给你两个只包含 0, 1 的 2 \times n 的数组 a, b,每次可以交换相邻两个数,问从 a 变成 b 最少需要交换多少次。

Solution

先看只有一行的情况:

我们考虑每两个相邻的点对答案的贡献,即交换的次数。

记两个数组 a, b 的前缀和分别为 sa, sb,枚举每一位 ans 加上 |sa_i - sb_i| 即为答案。这个应该比较好理解吧。

现在来看如果有两行如何处理:

两行比一行就多了一个上下交换的操作。

我们还是设 sa_{0/1, i} 表示 a 的第一,第二行的前缀和,sb_{0/1, i} 同理。

枚举每一位如果 sa_{0, i} > sb_{0, i} 且 sa_{1, i} < sb_{1, i} 或者 sa_{0, i} < sb_{1, i} 且 sa_{1, i} > sb_{1, i}那么我们上下交换,这样就从原本两次的左右交换变成了一次上下交换,节省了一次操作。

当然还要加上 |sa_{0, i} - sb_{0, i}| + |sa_{1, i} - sb_{1, i}|。

需要注意的是,sa 是在实时变化的,所以开两个变量来记 a 的前缀和。

最后别忘了判无解:如果 a, b 中 1 的个数不相同那么一定无解。

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("");
}