乍一听这题目我还以为是那类石子合并dp题呢🤣
Question:AcWing 4380.合并石子
Question Link:acwing.com/problem/content/4383
Question Analysis:
首先我们只能合并相邻的一堆,而且最后要求
a
i
′
=
b
i
′
a'_i=b'_i
ai′=bi′成立,所以我们应该从左到右开始枚举是否可以合成相同数量的石子堆,如果可以,立马开始下一个堆的合成,只有这样才能使堆的数量够大,这就是贪心。
1
≤
n
,
m
≤
1
0
5
1≤n,m≤10^5
1≤n,m≤105,我们至少要采用
n
l
o
g
n
nlogn
nlogn时间复杂度的算法,所以这里用了前缀和和双指针的用法。
AcWing给的算法标签:
贪心
前缀和
双指针
Code:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5+5;
int a[N],b[N],s1[N],s2[N];
int n,m,res;
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i ++ ) scanf("%d", &a[i]),s1[i]+=s1[i-1]+a[i];
for (int i = 1; i <= m; i ++ ) scanf("%d", &b[i]),s2[i]+=s2[i-1]+b[i];
int l=1,r=1;
if(s1[l]==s2[r]) res++;
while(l!=n||r!=m)
{
if(s1[l]>s2[r]) r++;
else l++;
if(s1[l]==s2[r]) res++;
}
printf("%d\n",res);
}
a,b数组可删去
这道题比赛的时候时学长做的今天小做一手🤗