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.
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).
Print the only integer a — the maximum strength Bob can achieve.
5 1 2 3 4 5 ABABA
11
5 1 2 3 4 5 AAAAA
15
1 1 B
1
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing.
题意:有n个元素,每个元素有一个力量值,再输入一个字符串,只有AB两种字符,每个字符对应一个元素值,你可以进行一次操作,把某个前缀或者后缀的A变成B,B变成A。(可以不进行操作),使得B对应的元素总力量值达到最大。
定义两个数组维护前缀和。元素的力量值要么属于A要么属于B,所以我们可以ans=max(ans,sum1[n]-sum1[i]+sum[i]),ans=max(ans,sum2[n]-sum2[i]+sum1[i])通过遍历1~n,来确定最大值
#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
#include<iomanip>
#include<cmath>
using namespace std;
const int maxn=5e5+5;
long long sum1[maxn],sum2[maxn],ans;
char s[maxn];
int n,a[maxn];
int main()
{
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
cin>>s+1;
for(int i=1;i<=n;i++){
sum1[i]=sum1[i-1];
sum2[i]=sum2[i-1];
if(s[i]=='A'){
sum1[i]+=a[i];
}
else{
sum2[i]+=a[i];
}
}
ans=max(sum1[n],sum2[n]);
for(int i=1;i<=n;i++){
ans=max(ans,sum1[n]+sum2[i]-sum1[i]);
ans=max(ans,sum2[n]+sum1[i]-sum2[i]);
}
cout<<ans<<endl;
return 0;
}