Codeforces 1036D Vasya and Arrays 题解 [ 黄 ] [ 双指针 ] [ 前缀和 ]

Vasya and Arrays:弱智题。

打 CF Bingo 的时候被这题硬控 1min,还被 Xlw6friend 喷糖了,我才是奶龙!!!!!!

先考虑什么时候有解,不难发现如果将所有数都合并到一起,如果此时两个数组还不同就一定无解。

而对于有解的情况,相当于我们要将两个序列进行分段,使得两个序列中对应的每一段都相等。因此从前往后用双指针扫描,遇到一个前缀和相等的前缀就直接在这里分段即可。因为每一次都是在前缀和相等的时候分段,所以可以证明对应的每一段都相等。

时间复杂度 \(O(n)\)

#include <bits/stdc++.h>
#define fi first
#define se second
#define eb(x) emplace_back(x)
#define pb(x) push_back(x)
#define lc(x) (tr[x].ls)
#define rc(x) (tr[x].rs)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ldb;
using pi = pair<int, int>;
const int N = 300005;
int n, m, ans;
ll a[N], b[N];
int main()
{
    //freopen("sample.in", "r", stdin);
    //freopen("sample.out", "w", stdout);
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n;
    for(int i = 1; i <= n; i++)
    {
        cin >> a[i];
        a[i] += a[i - 1];
    }
    cin >> m;
    for(int i = 1; i <= m; i++)
    {
        cin >> b[i];
        b[i] += b[i - 1];
    }    
    if(a[n] != b[m])
    {
        cout << -1;
        return 0;
    }
    int p = 0;
    for(int i = 1; i <= n; i++)
    {
        while(p < m && b[p] < a[i]) p++;
        if(b[p] == a[i]) ans++;
    }
    cout << ans;
    return 0;
}
posted @ 2025-08-30 14:27  KS_Fszha  阅读(1)  评论(0)    收藏  举报