思路

先计算一个d数组,用于存储a和b中每个元素之间的差值,题目是进行若干次操作,使得a=b,即d数组元素均为0。
所以要使得d数组均为0,就要设定一个s计算前缀差,每一次都要先计算前缀差,再计算ans值,ans值也就等于llabs(s)/2。

AC代码

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define fi first
#define se second
#define pb push_back
#define pp pop_back
#define pf push_front
#define lb lower_bound
#define ub upper_bound
#define UNIQUE(v) sort(all(v)); v.erase(unique(all(v)), v.end())
#define all(v) v.begin(), v.end()
#define sz(v) (int)v.size()
#define PQ priority_queue
constexpr ll inf = 1e9 + 7;

void solve() {
    int n;
    cin >> n;
    vector<ll> a(n), b(n);
    for (int i = 0; i < n; i++) cin >> a[i];
    for (int i = 0; i < n; i++) cin >> b[i];
    ll sa = 0;
    ll sb = 0;
    ll ans = 0;
    for (int i = 0; i < n; i++)
    {
        if (abs(a[i] - b[i]) % 2 != 0) {
            cout << -1 << "\n";
            return ;
        }
        sa += a[i];
        sb += b[i];
    }
    if (sa != sb) {
        cout << -1 << '\n';
        return ;
    }
    ll s = 0;
    for (int i = 0; i < n; i++) {
        s += (a[i] - b[i]);
        ans += llabs(s) / 2;
    }
    cout << ans << "\n";
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t; cin >> t;
    while (t--) solve();
    return 0;
}