B - Alice, Bob, Two Teams
Time Limit:1500MS Memory Limit:262144KB 64bit IO Format:%I64d & %I64u
Submit
Status
Practice
CodeForces 632B
Description
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice’s initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 ≤ n ≤ 5·105) — the number of game pieces.
The second line contains n integers pi (1 ≤ pi ≤ 109) — the strength of the i-th piece.
The third line contains n characters A or B — the assignment of teams after the first step (after Alice’s step).
Output
Print the only integer a — the maximum strength Bob can achieve.
Sample Input
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
题意:第一行输入n,第二行输入n个int型整数,第三行输入n个字母,字母只会是A或者B,输出B代表的数字和。注意有一次更改前缀或者后缀的机会(就是把A改成B,或者把B改成A)。
这里更改的是前缀或后缀,而不是单独的某一个字母。
例如 字符串abcd,前缀就有a,ab,abc,abcd,后缀就有d,dc,dcb,dcba。(事实证明带本字典去比赛是多么明智)
接收数据后分别得出A和B的总数,然后模拟更改前缀或者后缀,最终得到B的最大值
代码
#include <iostream>
#include<algorithm>
#include<stdio.h>
#include<math.h>
#include<string>
#include<string.h>
using namespace std;
int n;//字符串长度
long long int num[500005];//存储数字
char str[500005];//存储AB
long long int sum_A[500005];//A的前i位和
long long int sum_B[500005];//B的前i位和
long long int max_sum;//最大和
int main()
{
while(~scanf("%d",&n))
{
memset(num,0,sizeof(num));//全部初始化
memset(str,'\0',sizeof(str));
memset(sum_A,0,sizeof(sum_A));
memset(sum_B,0,sizeof(sum_B));
for(int i=1; i<=n; i++)
scanf("%I64d",&num[i]);
scanf("%s",str+1);//一定要从数组第一位开始接收数据
for(int i=1; i<=n; i++)
{
sum_A[i]=sum_A[i-1];
sum_B[i]=sum_B[i-1];
if(str[i]=='A')//加到A队
sum_A[i]+=num[i];
else if(str[i]=='B')
sum_B[i]+=num[i];
}
max_sum=0;//初始化最大值
max_sum=max(sum_A[n],sum_B[n]);
for(int i=1; i<=n; i++)
{//模拟改变前缀或后缀
max_sum=max(max_sum,sum_B[n]-sum_B[i]+sum_A[i]);
max_sum=max(max_sum,sum_A[n]-sum_A[i]+sum_B[i]);
}
printf("%I64d\n",max_sum);
}
return 0;
}