D. Vasya and Arrays

Vasya has two arrays A and B of lengths n and m, respectively.

He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1,10,100,1000,10000] Vasya can obtain array [1,1110,10000], and from array [1,2,3] Vasya can obtain array [6].

Two arrays A and B are considered equal if and only if they have the same length and for each valid i Ai=Bi.

Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.

Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.

Input
The first line contains a single integer n (1≤n≤3⋅105) — the length of the first array.

The second line contains n integers a1,a2,⋯,an (1≤ai≤109) — elements of the array A.

The third line contains a single integer m (1≤m≤3⋅105) — the length of the second array.

The fourth line contains m integers b1,b2,⋯,bm (1≤bi≤109) - elements of the array B.

Output
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays
A and B in such a way that they became equal.

If there is no way to make array equal, print “-1”.

Examples
inputCopy
5
11 2 3 5 7
4
11 7 3 7
output
3
input
2
1 2
1
100
output
-1
inputCopy
3
1 2 3
3
1 2 3
output
3

#include<bits/stdc++.h>
#define endl '\n'
#define pb push_back
#define mp make_pair
#define _ ios::sync_with_stdio(false)
bool SUBMIT = 1;
typedef long long ll;
using namespace std;
const double PI = acos(-1);
ll n,m;
const int inf =300000+1000;
ll s1[inf],s2[inf];
int main()
{
    if(!SUBMIT)freopen("i.txt","r",stdin);else _;
    cin>>n;
    for(int i=0;i<n;i++)cin>>s1[i];
    cin>>m;
    for(int i=0;i<m;i++)cin>>s2[i];
    ll ans=0;bool f=false;
    ll k1=0,k2=0,u=0;
    for(int i=0;i<n;i++)
    {
        k1+=s1[i];
        while(k2<k1&&u<m)k2+=s2[u++];
        if(k1==k2){
            k1=0,k2=0;
            ans++;continue;
        }
        if(k1<k2)continue;
        if(u>=m){
            f=true;break;
        }
    }
    if(!f&&u>=m&&k1==k2)cout<<ans<<endl;
    else cout<<"-1"<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38701476/article/details/82560064