(map)前缀和和后缀和相等的最大值-CF-1006C

问题链接

问题:

把字符串分成三部分,每一部分可以为空,问第一部分和第三部分相等的最大值,

如果不存在相等的值 输出 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;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值