问题链接
问题:
把字符串分成三部分,每一部分可以为空,问第一部分和第三部分相等的最大值,
如果不存在相等的值 输出 0
Input
5 1 3 1 1 4
Output
5 Input 3 4 1 2
Output
0
分析:
1. 用两个数组记录所有的 前缀和 和 后缀和
2. 同时用 map<int, int> 记录每个前缀和后缀出现的位置,方便之后的操作。first是和,second是位置
3. 再用一个 map<int ,int> book ;来记录某一个后缀和出现过,出现过就把 second = 1;
4. 遍历每一个前缀和,如果 (book[ 前缀和 ] == 1 && 前缀和的位置 < 这个后缀和的位置),ans = max(ans,前缀和)
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <map>
#include <stdio.h>
using namespace std;
typedef long long LL;
const int MAXN = 1e6;
LL a[MAXN];
LL f[MAXN];
LL l[MAXN];
map <LL,int> book;
map <LL,int> F_id;
map <LL,int> L_id;
int main()
{
book.clear();
memset(f,0,sizeof(f));
memset(l,0,sizeof(l));
LL n;
cin >> n ;
for (int i = 1; i <= n; i++)
{
scanf("%lld",&a[i]);
f[i] = a[i] + f[i - 1];
F_id[f[i]] = i;
}
for (int i = 1; i <= n; i++)
{
l[i] = l[i - 1] + a[n-i+1];
L_id[l[i]] = n-i+1;
book[l[i]] = 1;
}
LL ans = 0;
for (int i = 1; i <= n; i++)
{
if (book[f[i]] )
{
if(F_id[f[i]] < L_id[f[i]])
ans = max(ans, f[i]);
else
break;
}
}
printf("%lld\n",ans);
return 0;
}