codeforces 1036D

该博客讨论了一个关于数组操作的问题,其中Vasya有两个数组A和B,他可以任意次数地将数组中连续子段替换为其元素之和。目标是通过这些操作使A和B变得相等,并且使得最终的数组长度最大。如果两个数组的总和相等,那么总是有解的,即至少可以将所有元素合并成一个数组。博客提供了AC代码来解决这个问题,但指出使用cin读取输入可能会导致超时,而使用scanf则不会。
摘要由CSDN通过智能技术生成

原题

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”.

传送门

题意

有两个数组,可以将数组内连续的一部分元素加起来,使这两个数组完全相等,然后求两数组完全相等之后最长的数组长度。如果两个数组无法做到相等,就输出-1。

思路

分析得出,两个数组总和相等,则必然有解,因为至少可以取全部合并。

如果两数组总和不相等,则输出-1。

无论如何合并,第一组必然包含首元素,所以直接从首元素开始合并最方便。

AC代码

#include<iostream>
using namespace std;

long long a[300005],b[300005];
long long suma,sumb;
int n,m;

int main()
{
	cin>>n;
	for(int i = 1;i<= n;i++)
	{
		scanf("%lld",&a[i]);
		suma+= a[i];
	}
	cin>>m;
	for(int i = 1;i<= m;i++)
	{
		scanf("%lld",&b[i]);
		sumb+= b[i];
	}
	if(suma!= sumb)cout<<-1<<endl;
	else
	{
		long long aa = 0,bb = 0;//aa和bb是两组从首元素开始的和 
		int x = 1,y = 1;
		int ans=0;
		while(x<= n||y<= m)
		{
			if(aa<= bb)
			{
				aa+= a[x++];
			}
			else
			{
				bb+= b[y++];
			}
			if(aa==bb)
			{
				ans+= 1;//每相等一次就代表两数组的前某部分相等,更新长度 
			}
		}
		cout<<ans<<endl;
	}
}

有一个问题是输入数组时使用cin会超时,scanf不会超,我看有大佬cin也不超时,前路漫长啊

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值