#include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>

//using namespace __gnu_pbds;
using namespace std;

#pragma comment(linker, "/STACK:16777216")

#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define mp make_pair
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define pow2(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) (((x)<<1)+1)
#define R(x) (((x)<<1)+2)
#define umap unordered_map
#define double long double
#define mod 1000000007
#define mod1 10000019
#define LIMIT 40000000000000000LL
#define MAX1 1000000000
//#define si(n) scanf("%d",&n)
//#define sii(n,m) scanf("%d%d",&n,&m)
//#define pi(n) printf("%d\n",n)
const int inf=0x3f3f3f3f;
// const long double pi=acos(-1.0);
#define INF 1000000000000000000LL
#define inf 2000000000
#define MAX 1000005
#define N 600010
const string debug_line="yolo";
#define debug error(debug_line)
// const double PI=4*atan(1);
#define read() freopen("mergedoutput.txt","r",stdin)
#define write() freopen("output.txt","w",stdout)
//template <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;

typedef struct node2{
	ll val;
	ll lazyp;
	bool islazyp;
}node1;

node1 tree[2400100];
vi Adj[600100];
bool visited[600100];
vector<pii> add[600100];
vector<pii> del[600100];
int dfs_timer=0;
int begin1[600100];
int end1[600100];
int timerWork[600100];
ll dp[600100];
int n,m;

void initialise(int node,int b,int e){
	if(b>e){
		return ;
	}
	else if(b==e){
		tree[node].val=LIMIT;
		tree[node].lazyp=0;
		tree[node].islazyp=0;
		return ;
	}
	else{
		initialise(2*node,b,(b+e)/2);
		initialise(2*node+1,(b+e)/2+1,e);
		tree[node].val=LIMIT;
		tree[node].lazyp=0;
		tree[node].islazyp=0;
		return ;
	}
}

void updatev(int node,int b,int e,int index,ll val){
	if(tree[node].islazyp){
		tree[node].val+=tree[node].lazyp;
		if(b!=e){
			tree[2*node].lazyp+=tree[node].lazyp;
			tree[2*node+1].lazyp+=tree[node].lazyp;
			tree[2*node].islazyp=tree[2*node+1].islazyp=true;
		}
		tree[node].islazyp=false;
		tree[node].lazyp=0;
	}
	if(b>e){
		return ;
	}
	else if(b==e && e==index){
		tree[node].val=val;
		return ;
	}
	else{
		if(index<=(b+e)/2){
			updatev(2*node,b,(b+e)/2,index,val);
		}
		else{
			updatev(2*node+1,(b+e)/2+1,e,index,val);
		}
		tree[node].val=min(tree[2*node].val,tree[2*node+1].val);
		return ;
	}
}

void updated(int node,int b,int e,int i,int j,ll val){
	// printf("before (%d,%d)->(%d)\n",b,e,tree[node].val);
	if(tree[node].islazyp){
		tree[node].val+=tree[node].lazyp;
		if(b!=e){
			tree[2*node].lazyp+=tree[node].lazyp;
			tree[2*node+1].lazyp+=tree[node].lazyp;
			tree[2*node].islazyp=tree[2*node+1].islazyp=true;
		}
		tree[node].islazyp=false;
		tree[node].lazyp=0;
	}
	if(b>e || i>e || j<b){
		return ;
	}
	else if(i<=b && e<=j){
		tree[node].val+=val;
		if(b!=e){
			tree[2*node].lazyp+=val;
			tree[2*node+1].lazyp+=val;
			tree[2*node].islazyp=tree[2*node+1].islazyp=true;
		}
		return ;
	}
	else{
		updated(2*node,b,(b+e)/2,i,j,val);
		updated(2*node+1,(b+e)/2+1,e,i,j,val);
		tree[node].val=min(tree[2*node].val,tree[2*node+1].val);
		// printf("(%d,%d)->(%d)\n",b,e,tree[node].val);
		return ;
	}
}

void query(node1 &res,int node,int b,int e,int i,int j){
	if(tree[node].islazyp){
		tree[node].val+=tree[node].lazyp;
		if(b!=e){
			tree[2*node].lazyp+=tree[node].lazyp;
			tree[2*node+1].lazyp+=tree[node].lazyp;
			tree[2*node].islazyp=tree[2*node+1].islazyp=true;
		}
		tree[node].islazyp=false;
		tree[node].lazyp=0;
	}
	if(b>e || i>e || j<b){
		return ;
	}
	else if(i<=b && e<=j){
		res=tree[node];
		return ;
	}
	else{
		node1 l,r;
		l.val=r.val=LIMIT;
		query(l,2*node,b,(b+e)/2,i,j);
		query(r,2*node+1,(b+e)/2+1,e,i,j);
		res.val=min(l.val,r.val);
		return ;
	}
}

ll solve(int u,int p){
	visited[u]=true;
	ll prev=0;

	rep(t1,Adj[u]){
		if(!visited[t1] && t1!=p){
			prev+=solve(t1,u);
			if(prev!=2*LIMIT){
				prev=min(prev,2*LIMIT);
			}
		}
	}

	if(u==1){
		dp[u]=prev;
		return dp[u];
	}

	rep(t1,add[u]){
		assert(t1.y+prev>=t1.y && t1.y+prev>=prev);
		// error(t1.y+prev);
		updatev(1,1,m,timerWork[t1.x],t1.y+prev);
	}

	rep(t1,del[u]){
		updatev(1,1,m,timerWork[t1.x],LIMIT);
	}

	rep(t1,Adj[u]){
		if(t1!=p){
			updated(1,1,m,begin1[t1],end1[t1],prev-dp[t1]);
		}
	}

	node1 res;
	res.val=LIMIT;
	query(res,1,1,m,begin1[u],end1[u]);
	dp[u]=res.val;
	// Error(u,dp[u]);
	// Error(u,p);
	return dp[u];
}

void DFS(int u,int p){
	visited[u]=true;
	begin1[u]=dfs_timer+1;

	rep(t1,add[u]){
		timerWork[t1.x]=++dfs_timer;
	}

	rep(t1,Adj[u]){
		if(!visited[t1] && t1!=p){
			DFS(t1,u);
		}
	}
	end1[u]=dfs_timer;
	return ;
}

int main(){
	scanf("%d%d",&n,&m);

	For(i,1,n){
		int a,b;
		scanf("%d%d",&a,&b);
		Adj[a].pb(b);
		Adj[b].pb(a);
	}

	For(i,0,m){
		int u,v,c;
		scanf("%d%d%d",&u,&v,&c);
		add[u].pb(mp(i,c));
		del[v].pb(mp(i,c));
	}

	//initialise(1,1,m);
	debug;

	DFS(1,0);
	debug;

	For(i,0,n+1){
		visited[i]=false;
	}

	ll answer1=solve(1,0);

	if(!(answer1>=LIMIT)){
		printf("%lld\n",answer1);
	}
	else{
		printf("-1\n");
	}
return 0;}


#include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>

//using namespace __gnu_pbds;
using namespace std;

#pragma comment(linker, "/STACK:16777216")

#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define mp make_pair
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define pow2(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) (((x)<<1)+1)
#define R(x) (((x)<<1)+2)
#define umap unordered_map
#define double long double
#define mod 1000000007
#define mod1 10000019
#define LIMIT 40000000000000000LL
#define MAX1 1000000000
//#define si(n) scanf("%d",&n)
//#define sii(n,m) scanf("%d%d",&n,&m)
//#define pi(n) printf("%d\n",n)
const int inf=0x3f3f3f3f;
// const long double pi=acos(-1.0);
#define INF 1000000000000000000LL
#define inf 2000000000
#define MAX 1000005
#define N 600010
const string debug_line="yolo";
#define debug error(debug_line)
// const double PI=4*atan(1);
#define read() freopen("mergedoutput.txt","r",stdin)
#define write() freopen("output.txt","w",stdout)
//template <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;

typedef struct node2{
	ll val;
	ll lazyp;
	bool islazyp;
}node1;

node1 tree[2400100];
vi Adj[600100];
bool visited[600100];
vector<pii> add[600100];
vector<pii> del[600100];
int dfs_timer=0;
int begin1[600100];
int end1[600100];
int timerWork[600100];
ll dp[600100];
int n,m;

void initialise(int node,int b,int e){
	if(b>e){
		return ;
	}
	else if(b==e){
		tree[node].val=LIMIT;
		tree[node].lazyp=0;
		tree[node].islazyp=0;
		return ;
	}
	else{
		initialise(2*node,b,(b+e)/2);
		initialise(2*node+1,(b+e)/2+1,e);
		tree[node].val=LIMIT;
		tree[node].lazyp=0;
		tree[node].islazyp=0;
		return ;
	}
}

void updatev(int node,int b,int e,int index,ll val){
	if(tree[node].islazyp){
		tree[node].val+=tree[node].lazyp;
		tree[node].val=min(tree[node].val,LIMIT);
		if(b!=e){
			tree[2*node].lazyp+=tree[node].lazyp;
			tree[2*node+1].lazyp+=tree[node].lazyp;
			tree[2*node].islazyp=tree[2*node+1].islazyp=true;
		}
		tree[node].islazyp=false;
		tree[node].lazyp=0;
	}
	if(b>e){
		return ;
	}
	else if(b==e && e==index){
		tree[node].val=val;
		return ;
	}
	else{
		if(index<=(b+e)/2){
			updatev(2*node,b,(b+e)/2,index,val);
		}
		else{
			updatev(2*node+1,(b+e)/2+1,e,index,val);
		}
		tree[node].val=min(tree[2*node].val,tree[2*node+1].val);
		return ;
	}
}

void updated(int node,int b,int e,int i,int j,ll val){
	// printf("before (%d,%d)->(%d)\n",b,e,tree[node].val);
	if(tree[node].islazyp){
		tree[node].val+=tree[node].lazyp;
		tree[node].val=min(tree[node].val,LIMIT);
		if(b!=e){
			tree[2*node].lazyp+=tree[node].lazyp;
			tree[2*node+1].lazyp+=tree[node].lazyp;
			tree[2*node].islazyp=tree[2*node+1].islazyp=true;
		}
		tree[node].islazyp=false;
		tree[node].lazyp=0;
	}
	if(b>e || i>e || j<b){
		return ;
	}
	else if(i<=b && e<=j){
		tree[node].val+=val;
		tree[node].val=min(tree[node].val,LIMIT);
		if(b!=e){
			tree[2*node].lazyp+=val;
			tree[2*node+1].lazyp+=val;
			tree[2*node].islazyp=tree[2*node+1].islazyp=true;
		}
		return ;
	}
	else{
		updated(2*node,b,(b+e)/2,i,j,val);
		updated(2*node+1,(b+e)/2+1,e,i,j,val);
		tree[node].val=min(tree[2*node].val,tree[2*node+1].val);
		// printf("(%d,%d)->(%d)\n",b,e,tree[node].val);
		return ;
	}
}

void query(node1 &res,int node,int b,int e,int i,int j){
	if(tree[node].islazyp){
		tree[node].val+=tree[node].lazyp;
		tree[node].val=min(tree[node].val,LIMIT);
		if(b!=e){
			tree[2*node].lazyp+=tree[node].lazyp;
			tree[2*node+1].lazyp+=tree[node].lazyp;
			tree[2*node].islazyp=tree[2*node+1].islazyp=true;
		}
		tree[node].islazyp=false;
		tree[node].lazyp=0;
	}
	if(b>e || i>e || j<b){
		return ;
	}
	else if(i<=b && e<=j){
		res=tree[node];
		return ;
	}
	else{
		node1 l,r;
		l.val=r.val=LIMIT;
		query(l,2*node,b,(b+e)/2,i,j);
		query(r,2*node+1,(b+e)/2+1,e,i,j);
		res.val=min(l.val,r.val);
		return ;
	}
}

ll solve(int u,int p){
	visited[u]=true;
	ll prev=0;

	rep(t1,Adj[u]){
		if(!visited[t1] && t1!=p){
			prev+=solve(t1,u);
			if(prev!=2*LIMIT){
				prev=min(prev,2*LIMIT);
			}
		}
	}

	if(u==1){
		dp[u]=prev;
		return dp[u];
	}

	rep(t1,add[u]){
		assert(t1.y+prev>=t1.y && t1.y+prev>=prev);
		// error(t1.y+prev);
		updatev(1,1,m,timerWork[t1.x],t1.y+prev);
	}

	rep(t1,del[u]){
		updatev(1,1,m,timerWork[t1.x],LIMIT);
	}

	rep(t1,Adj[u]){
		if(t1!=p){
			updated(1,1,m,begin1[t1],end1[t1],prev-dp[t1]);
		}
	}

	node1 res;
	res.val=LIMIT;
	query(res,1,1,m,begin1[u],end1[u]);
	dp[u]=res.val;
	// Error(u,dp[u]);
	// Error(u,p);
	return dp[u];
}

void DFS(int u,int p){
	visited[u]=true;
	begin1[u]=dfs_timer+1;

	rep(t1,add[u]){
		timerWork[t1.x]=++dfs_timer;
	}

	rep(t1,Adj[u]){
		if(!visited[t1] && t1!=p){
			DFS(t1,u);
		}
	}
	end1[u]=dfs_timer;
	return ;
}

int main(){
	scanf("%d%d",&n,&m);

	For(i,1,n){
		int a,b;
		scanf("%d%d",&a,&b);
		Adj[a].pb(b);
		Adj[b].pb(a);
	}

	For(i,0,m){
		int u,v,c;
		scanf("%d%d%d",&u,&v,&c);
		add[u].pb(mp(i,c));
		del[v].pb(mp(i,c));
	}

	initialise(1,1,m);

	DFS(1,0);
	debug;

	For(i,0,n+1){
		visited[i]=false;
	}

	ll answer1=solve(1,0);

	if(!(answer1>=LIMIT)){
		printf("%lld\n",answer1);
	}
	else{
		printf("-1\n");
	}
return 0;}


#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <sstream>
#include <time.h>
#include <stdlib.h>
#include <random>
#include <cmath>

using namespace std;

long long dp[50][2];

int main()
{
    cin.tie(0);
    ios_base::sync_with_stdio(0);
	int n;
	cin >> n;
	long long suma = 0, sumb = 0;
	vector<long long> v(n);
	for(int i = 0; i < n; ++i)
		cin >> v[i];
	string s;
	cin >> s;
	long long mx = 0, cur = 0;
	for(int i = 0; i < n; ++i)
	{
		if(s[i] == 'B')
			sumb += v[i];
	}
	cur = sumb;
	for(int i = 0; i < n; ++i)
	{
		if(sumb > mx)
			mx = sumb;

		if(s[i] == 'B')
			sumb -= v[i];
		else
			sumb += v[i];

		if(sumb > mx)
			mx = sumb;
	}
	sumb = cur;

	for(int i = n-1; i >= 0; --i)
	{
		if(sumb > mx)
			mx = sumb;

		if(s[i] == 'B')
			sumb -= v[i];
		else
			sumb += v[i];

		if(sumb > mx)
			mx = sumb;
	}
	cout << mx;
    return 0;
}


#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=550000;
typedef long long ll;
ll f[N];
ll fA[N],fB[N];
int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
	for(int i=0;i<n;i++)
	scanf("%I64d",&f[i]);
	char ch[N];
	scanf("%s",ch);
	int m=strlen(ch);
	ll ans=0;
	fA[0]=ch[0]=='A'?f[0]:0;
	fB[0]=ch[0]=='B'?f[0]:0;
	for(int i=1;i<n;i++)
	{
        if(ch[i]=='A')
        fA[i]=fA[i-1]+f[i];
        else
        fA[i]=fA[i-1];
        if(ch[i]=='B')
        fB[i]=fB[i-1]+f[i];
        else
        fB[i]=fB[i-1];
	}
/*	for(int i=0;i<n;i++)
	{
		printf("%d %d\n",fA[i],fB[i]);
	}*/
	for(int i=0;i<n;i++)
	{
		ll cnt=fA[i]+fB[n-1]-fB[i];
		ans=max(ans,cnt);
	}
	for(int i=n-1;i>=0;i--)
	{
		ll cnt=fB[i-1]+fA[i]-fA[i-1];
		ans=max(ans,cnt);
	}
	printf("%I64d\n",ans);
}
return 0;
}


#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=550000;
typedef long long ll;
ll f[N];
ll fA[N],fB[N];
int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
	for(int i=1;i<=n;i++)
	scanf("%I64d",&f[i]);
	char ch[N];
	scanf("%s",ch+1);
	int m=strlen(ch+1);
	ll ans=0;
	fA[0]=0;
	fB[0]=0;
	for(int i=1;i<=n;i++)
	{
        if(ch[i]=='A')
        fA[i]=fA[i-1]+f[i];
        else
        fA[i]=fA[i-1];
        if(ch[i]=='B')
        fB[i]=fB[i-1]+f[i];
        else
        fB[i]=fB[i-1];
	}
     fA[n+1]=fA[n];
     fB[n+1]=fB[n];
	for(int i=0;i<=n;i++)
	{
		ll cnt=fA[i]+fB[n+1]-fB[i];
		ans=max(ans,cnt);
	}
     for(int i=0;i<=n;i++)
     {
     	ll cnt=fB[i]+fA[n+1]-fA[i];
		 ans=max(ans,cnt);
     }
	printf("%I64d\n",ans);
}
return 0;
}


#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=550000;
typedef long long ll;
ll f[N];
ll fA[N],fB[N];
int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
	for(int i=1;i<=n;i++)
	scanf("%I64d",&f[i]);
	char ch[N];
	scanf("%s",ch+1);
	int m=strlen(ch+1);
	ll ans=0;
	fA[0]=0;
	fB[0]=0;
	for(int i=1;i<=n;i++)
	{
        if(ch[i]=='A')
        fA[i]=fA[i-1]+f[i];
        else
        fA[i]=fA[i-1];
        if(ch[i]=='B')
        fB[i]=fB[i-1]+f[i];
        else
        fB[i]=fB[i-1];
	}
     fA[n+1]=fA[n];
     fB[n+1]=fB[n];
	for(int i=0;i<=n;i++)
	{
		ll cnt=fA[i]+fB[n+1]-fB[i];
		ans=max(ans,cnt);
	}
	for(int i=n;i>=0;i--)
	{
		ll cnt=fB[i-1]+fA[i]-fA[i-1];
		ans=max(ans,cnt);
	}
	printf("%I64d\n",ans);
}
return 0;
}


#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;
int main()
{
	int n ;
	cin>>n;
	vector<int >mas(n);
	for (int i = 0; i < n; i++)
	{
		cin>>mas[i];
	}
	string s;
	cin>>s;
	unsigned	long long  max=0, sum=0;

	unsigned long long  sum0=0;
	for (int i = 0; i < n; i++)
	{
		if(s[i]=='B') sum0+=mas[i];
	}
	if(sum0>max) max=sum0;

	sum=sum0;
	for (int i = 0; i < n; i++)
	{
		if(s[i]=='B')
		{
			sum-=mas[i];
		}
		else
			sum+=mas[i];

		if(sum>max) max=sum;
	}

	sum=sum0;
for (int i = n-1; i >=0; i--)
	{
		if(s[i]=='B')
		{
			sum-=mas[i];
		}
		else
			sum+=mas[i];

		if(sum>max) max=sum;
	}

cout<<max;
	return 0;
}


#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;
int main()
{
	int n ;
	cin>>n;
	vector<int >mas(n);
	for (int i = 0; i < n; i++)
	{
		cin>>mas[i];
	}
	string s;
	cin>>s;
	long long max=0, sum=0;

	long sum0=0;
	for (int i = 0; i < n; i++)
	{
		if(s[i]=='B') sum0+=mas[i];
	}
	if(sum0>max) max=sum0;

	sum=sum0;
	for (int i = 0; i < n; i++)
	{
		if(s[i]=='B')
		{
			sum-=mas[i];
		}
		else
			sum+=mas[i];

		if(sum>max) max=sum;
	}

	sum=sum0;
for (int i = n-1; i >=0; i--)
	{
		if(s[i]=='B')
		{
			sum-=mas[i];
		}
		else
			sum+=mas[i];

		if(sum>max) max=sum;
	}

cout<<max;
	return 0;
}


#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;
int main()
{
	int n ;
	cin>>n;
	vector<int >mas(n);
	for (int i = 0; i < n; i++)
	{
		cin>>mas[i];
	}
	string s;
	cin>>s;
	unsigned	long long max=0, sum=0;

	unsigned long sum0=0;
	for (int i = 0; i < n; i++)
	{
		if(s[i]=='B') sum0+=mas[i];
	}
	if(sum0>max) max=sum0;

	sum=sum0;
	for (int i = 0; i < n; i++)
	{
		if(s[i]=='B')
		{
			sum-=mas[i];
		}
		else
			sum+=mas[i];

		if(sum>max) max=sum;
	}

	sum=sum0;
for (int i = n-1; i >=0; i--)
	{
		if(s[i]=='B')
		{
			sum-=mas[i];
		}
		else
			sum+=mas[i];

		if(sum>max) max=sum;
	}

cout<<max;
	return 0;
}


#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;
int main()
{
	int n ;
	cin>>n;
	vector<int >mas(n);
	for (int i = 0; i < n; i++)
	{
		cin>>mas[i];
	}
	string s;
	cin>>s;
	unsigned	long long int max=0, sum=0;

	unsigned long long int sum0=0;
	for (int i = 0; i < n; i++)
	{
		if(s[i]=='B') sum0+=mas[i];
	}
	if(sum0>max) max=sum0;

	sum=sum0;
	for (int i = 0; i < n; i++)
	{
		if(s[i]=='B')
		{
			sum-=mas[i];
		}
		else
			sum+=mas[i];

		if(sum>max) max=sum;
	}

	sum=sum0;
for (int i = n-1; i >=0; i--)
	{
		if(s[i]=='B')
		{
			sum-=mas[i];
		}
		else
			sum+=mas[i];

		if(sum>max) max=sum;
	}

cout<<max;
	return 0;
}


#pragma comment (linker,"/stack:102400000,102400000")
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
#include<functional>
#include<iostream>
#include<string>
using namespace std;
const double PI=acos(-1.0);
#define N 500051
#define inf 0x7fffffff
#define fib 112233
#define mod 100007
#define ll __int64
#define able puts("0000000000000000000000")
template<class T_T> T_T f_max(T_T a,T_T b) { return a>b?a:b; }
template<class T_T> T_T f_min(T_T a,T_T b) { return a<b?a:b; }
template<class T_T> T_T f_abs(T_T a) { return a>0?a:-a; }
template<class T_T> T_T gcd(T_T a,T_T b){ return b?gcd(b,a%b):a; }
template<class T_T> void swap(T_T *a,T_T *b){T_T c;c=a;a=b;b=c;}
int n,m;
int num[N];
char mp[N];
ll sa[2][N],sb[2][N];
int main()
{
    int q,w,e,r;
    int i,j,k;
    int t;
	ll ans;
	while(~scanf("%d",&n)){
		for(i=1;i<=n;i++){
			scanf("%d",&num[i]);
		}
		scanf("%s",&mp[1]);
		sa[0][0]=sb[0][0]=0;
		sa[1][n+1]=sb[1][n+1]=0;
		for(i=1;i<=n;i++){
			sa[0][i]=sa[0][i-1];
			sb[0][i]=sb[0][i-1];
			if(mp[i]=='A'){
				sa[0][i]+=num[i];
			}
			else sb[0][i]+=num[i];
		}
		for(i=n;i;i--){
			sa[1][i]=sa[1][i+1];
			sb[1][i]=sb[1][i+1];
			if(mp[i]=='A'){
				sa[1][i]+=num[i];
			}
			else sb[1][i]+=num[i];
		}
		ans=0;
		for(i=0;i<=n;i++){
			ans=f_max(ans,sa[0][i]+sb[1][i+1]);
			ans=f_max(ans,sb[0][i]+sa[1][i+1]);
		}
		printf("%I64d\n",ans);
	}
    return 0;
}


// rc.cpp : Defines the entry point for the console application.
//

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <functional>

using namespace std;

typedef unsigned char uchar;
typedef unsigned int uint;
typedef unsigned long long uint64;
typedef long long sint64;

char a[500001];
uint64 v[500000],
       lr[500001];

int main(int argc, char* argv[])
{
    uint64 n;
    cin >> n;

    uint64 s = 0;
    for (uint64 i = 0; i < n; ++i)
    {
        cin >> v[i];
        s += v[i];
    }

    cin >> a;

    for (uint64 i = 1; i <= n; ++i)
        lr[i] = lr[i - 1] + (a[i - 1] == 'B' ? v[i - 1] : 0);

    uint64 mx = 0,
           cc = 0;
    for (uint64 i = 0; i <= n; ++i)
    {
        uint64 c = cc + lr[n] - lr[i];
        if (c > mx)
            mx = c;

        if (i < n)
            cc += a[i] == 'A' ? v[i] : 0;
    }

    cc = 0;
    for (uint64 i = n - 1; i != -2; --i)
    {
        uint64 c = cc + lr[i + 1];
        if (c > mx)
            mx = c;

        if (i != -1)
            cc += a[i] == 'A' ? v[i] : 0;
    }

    cout << mx << endl;

    return 0;
}


#include <vector>
#include <iostream>
#include <string>
using namespace std;

int main (){
    long long a, sum = 0, min = 10000000000000000;
    cin >> a;
    char c;
    string s;
    vector <long long> v(a + 2);
    vector <long long> pref(a + 2);
    vector <long long> suff(a + 2);
    pref[0] = 0;
    for (int i = 0; i < a; i++){
        cin >> v[i];
    }
    getline (cin, s);
    getline (cin, s);

    for (int i = 0; i < s.length(); i++){
        c = s[i];
        if (i != 0){
            if (c == 'B') pref[i] = pref[i - 1] + v[i], sum += v[i];
            else pref[i] = pref[i - 1] - v[i];
        }
        else {
            if (c == 'B') pref[i] = pref[0] + v[i], sum += v[i];
            else pref[i] = pref[0] - v[i];
        }
        if (pref[i] < min) min = pref[i];
    }
    for (int i = s.length() - 1; i >= 0; i--){
        c = s[i];
        if (i != s.length() - 1){
            if (c == 'B') suff[i] = suff[i + 1] + v[i];
            else suff[i] = suff[i + 1] - v[i];
        }
        else {
            if (c == 'B') suff[i] = suff[s.length() - 1] + v[i];
            else suff[i] = suff[s.length() - 1] - v[i];
        }
        if (suff[i] < min) min = suff[i];
    }
    if (min < 0) cout << sum - min;
    else cout << sum;

}


#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
	vector < pair <long long , long long > > vec(500001);
	long long num,a=0,b=0,sum=0,max=0;
	cin >> num;
	string s;
	for (int i = 0; i < num; i++)
	{
		cin >> vec[i].second;
	}
	cin >> s;
	for (int i = 0; i < num; i++)
	{
		if (s[i] == 'A')
		{
			vec[i].first = a + vec[i].second;
			a = a + vec[i].second;
		}
		else
		{
			vec[i].first = b + vec[i].second;
			b = b + vec[i].second;
		}
	}
	a = 0; b = 0;
	for (int i = num-1; i >= 0; i--)
	{
		if (s[i] == 'A')
		{
			vec[i].second = a + vec[i].second;
			a =  vec[i].second;
		}
		else
		{
			vec[i].second = b + vec[i].second;
			b = vec[i].second;
		}

	}
	s = '.' + s;
	pair <long, long> c;
	c.first = 0;
	c.second = 0;
	vec.insert(vec.begin(),c);
	for (int i = 0; i <num + 2; i++)
	{
		if ((i != num + 1) && s[i] == 'B' && s[i + 1] == 'A')
		{
			sum = vec[i].first + vec[i + 1].second;
			if (sum > max)
				max = sum;
		}
		if ((i>0) && (s[i]=='B'&& s[i-1]=='A'))
		{
			sum = vec[i].second + vec[i - 1].first;
			if (sum > max)
				max = sum;
		}
	}
	if (a > b)
	{
		b = a;
	}
	if (max < b)
		max = b;

	cout << max << endl;
}


#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
	vector < pair <long long , long long > > vec(500001);
	long long num,a=0,b=0,sum=0,max=0;
	cin >> num;
	string s;
	for (int i = 0; i < num; i++)
	{
		cin >> vec[i].second;
	}
	cin >> s;
	for (int i = 0; i < num; i++)
	{
		if (s[i] == 'A')
		{
			vec[i].first = a + vec[i].second;
			a = a + vec[i].second;
		}
		else
		{
			vec[i].first = b + vec[i].second;
			b = b + vec[i].second;
		}
	}
	a = 0; b = 0;
	for (int i = num-1; i >= 0; i--)
	{
		if (s[i] == 'A')
		{
			vec[i].second = a + vec[i].second;
			a =  vec[i].second;
		}
		else
		{
			vec[i].second = b + vec[i].second;
			b = vec[i].second;
		}

	}
	s = '.' + s;
	pair <long, long> c;
	c.first = 0;
	c.second = 0;
	vec.insert(vec.begin(),c);
	for (int i = 0; i <num + 2; i++)
	{
		if ((i != num + 1) && s[i] == 'B' && s[i + 1] == 'A')
		{
			sum = vec[i].first + vec[i + 1].second;
			if (sum > max)
				max = sum;
		}
		if ((i>0) && (s[i]=='B'&& s[i-1]=='A'))
		{
			sum = vec[i].second + vec[i - 1].first;
			if (sum > max)
				max = sum;
		}
	}
	cout << max << endl;
}


#define _CRT_SECURE_NO_WARNINGS
#include<math.h>
#include<map>
#include<iostream>
#include<string>
#include<algorithm>
#include<iomanip>
#include<stdio.h>
#include<set>
#include<vector>

#define forn(i,n) for(long long i=0;i<n;++i)
#define rforn(i,n) for(long long i=n-1;i>=0;--i)

using namespace std;

//#define TEST_RUN

long long a[500002];
long long di[500002];
int g[500002];
int main()
{
	#ifdef TEST_RUN
	double start_time = clock();
	//freopen("intput.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	#endif

	int n;
	cin >> n;
	long long sum=0;
	long long diff=0;
	forn(i, n)scanf("%d", &a[i]);
	string s;
	cin >>  s;
	forn(i, n)
		if (s[i] == 'A')g[i] = -1;
		else g[i] = 1;

	forn(i, n)
	{
		diff = diff +  g[i] *a[i];
		di[i] = diff;
		sum += a[i];
	}
	long long bestdiff;
	long long cur = 0;

	for (int i = n - 1;i >= 0;--i)
	{
		cur = cur - g[i] * a[i];
		if (i && cur + di[i - 1] > diff)diff = cur + di[i - 1];
		di[i] = cur;
	}
	if (cur > diff)diff = cur;

	cur = 0;
	di[n] = 0;
	for (int i = 0;i < n;++i)
	{
		cur = cur - g[i] * a[i];
		if (cur + di[i + 1] > diff)diff = cur + di[i + 1];
	}

	cout << (sum + diff) / 2 ;

	#ifdef TEST_RUN
	printf("\nRun time is %.2lf\n", (clock() - start_time)/ CLOCKS_PER_SEC);
	system("pause");
	#endif
}


#define _CRT_SECURE_NO_WARNINGS
#include<math.h>
#include<map>
#include<iostream>
#include<string>
#include<algorithm>
#include<iomanip>
#include<stdio.h>
#include<set>
#include<vector>

#define forn(i,n) for(long long i=0;i<n;++i)
#define rforn(i,n) for(long long i=n-1;i>=0;--i)

using namespace std;

//#define TEST_RUN

long long a[500002];
long long di[500002];
int g[500002];
int main()
{
	#ifdef TEST_RUN
	double start_time = clock();
	//freopen("intput.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	#endif

	int n;
	cin >> n;
	long long sum=0;
	long long diff=0;
	forn(i, n)scanf("%d", &a[i]);
	string s;
	cin >>  s;
	forn(i, n)
		if (s[i] == 'A')g[i] = -1;
		else g[i] = 1;

	forn(i, n)
	{
		diff = diff +  g[i] *a[i];
		di[i] = diff;
		sum += a[i];
	}
	long long bestdiff;
	long long cur = 0;

	for (int i = n - 1;i >= 0;--i)
	{
		cur = cur - g[i] * a[i];
		if (i && cur + di[i - 1] > diff)diff = cur + di[i - 1];
		di[i] = -cur;

	}
	if (cur > diff)diff = cur;

	cur = 0;
	di[n] = 0;
	for (int i = 0;i < n;++i)
	{
		cur = cur - g[i] * a[i];
		if (cur + di[i + 1] > diff)diff = cur + di[i + 1];
	}

	cout << (sum + diff) / 2 ;

	#ifdef TEST_RUN
	printf("\nRun time is %.2lf\n", (clock() - start_time)/ CLOCKS_PER_SEC);
	system("pause");
	#endif
}


#define _CRT_SECURE_NO_WARNINGS
#include<math.h>
#include<map>
#include<iostream>
#include<string>
#include<algorithm>
#include<iomanip>
#include<stdio.h>
#include<set>
#include<vector>

#define forn(i,n) for(long long i=0;i<n;++i)
#define rforn(i,n) for(long long i=n-1;i>=0;--i)

using namespace std;

//#define TEST_RUN

long long a[500002];
long long di[500002];
int g[500002];
int main()
{
	#ifdef TEST_RUN
	double start_time = clock();
	//freopen("intput.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	#endif

	int n;
	cin >> n;
	long long sum=0;
	long long diff=0;
	forn(i, n)scanf("%d", &a[i]);
	string s;
	cin >>  s;
	forn(i, n)
		if (s[i] == 'A')g[i] = -1;
		else g[i] = 1;

	forn(i, n)
	{
		diff = diff +  g[i] *a[i];
		di[i] = diff;
		sum += a[i];
	}
	long long bestdiff;
	long long cur = 0;

	for (int i = n - 1;i >= 0;--i)
	{
		cur = cur - g[i] * a[i];
		if (i && cur + di[i - 1] > diff)diff = cur + di[i - 1];
		di[i] = cur;
	}
	if (cur > diff)diff = cur;

	cur = 0;
	di[n] = 0;
	for (int i = 0;i < n;++i)
	{
		cur = cur - g[i] * a[i];
		if (cur + di[i + 1] > diff)diff = cur + di[i + 1];
	}

	cout << (sum - diff) / 2 + diff;

	#ifdef TEST_RUN
	printf("\nRun time is %.2lf\n", (clock() - start_time)/ CLOCKS_PER_SEC);
	system("pause");
	#endif
}


//#define MYDEBUG
#define _CRT_SECURE_NO_WARNINGS
#define TASK "radio"
#pragma comment(linker, "/STACK:536870912")
#include <cstdio>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <functional>
#include <cassert>
#include <bitset>
#include <unordered_set>
#include <unordered_map>
#include <random>

const int MOD = 1296000;
const int INF = 1000000001;
const int MAXN = 17;
const long double EPS = 1e-6;
const int HASH_POW = 29;
const long double PI = acos(-1.0);

using namespace std;

void my_return(int code)
{
#ifdef MYDEBUG
	cout << "\nTime = " << fixed << setprecision(3) << double(clock()) / CLOCKS_PER_SEC << endl;
#endif
	exit(code);
}

int n, p[500010];
char s[500010];

int main()
{
	cin.sync_with_stdio(0);
	cin.tie(0);
	mt19937 mt_rand(time(0));
#ifdef MYDEBUG
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#else
	/*freopen(TASK".in", "rt", stdin);
	freopen(TASK".out", "wt", stdout);*/
	/*freopen("input.txt", "rt", stdin);
	freopen("output.txt", "wt", stdout);*/
#endif

	scanf("%d", &n);
	for (int i = 0; i < n; ++i)
		scanf("%d", &p[i]);
	scanf("%s", s);

	long long cur = 0, ans = 0;
	for (int i = 0; i < n; ++i)
		if (s[i] == 'B')
			cur += p[i];
	ans = max(ans, cur);
	for (int i = 0; i < n; ++i)
	{
		if (s[i] == 'A')
			cur += p[i];
		else
			cur -= p[i];
		ans = max(ans, cur);
	}
	for (int i = 0; n - 1 - i > i; ++i)
	{
		swap(p[i], p[n - 1 - i]);
		swap(s[i], s[n - 1 - i]);
	}
	cur = 0;
	for (int i = 0; i < n; ++i)
		if (s[i] == 'B')
			cur += p[i];
	ans = max(ans, cur);
	for (int i = 0; i < n; ++i)
	{
		if (s[i] == 'A')
			cur += p[i];
		else
			cur -= p[i];
		ans = max(ans, cur);
	}
	printf("%I64d\n", ans);

	my_return(0);
}


#define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#include <iostream>
#include <utility>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <climits>
#include <cstring>
#include <cmath>
#include <queue>
#include <functional>
#include <cstdio>
#include <cassert>
#include <stack>
#include <ctime>

#define mp make_pair
#define mt(x,y,z) mp((x), mp((y), (z)))
#define ZERO(x) memset((x), 0, sizeof(x))
#define NEGATE(x) memset((x), 255, sizeof(x))
using namespace std;

typedef long long ll;

int main()
{
#ifdef XXX
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

	ll n;
	scanf("%lld", &n);
	vector<ll> v(n);
	for (int i = 0; i < n; i++)
		scanf("%lld", &v[i]);

	string s;
	cin >> s;
	ll cur = 0;

	//reverse(s.begin(), s.end());
	//reverse(v.begin(), v.end());

	for (int i = 0; i < s.size(); i++)
		if (s[i] == 'B')
			cur += v[i];

	ll ans = cur;

	for (int i = 0; i < v.size(); i++)
	{
		if (s[i] == 'A')
			cur += v[i];
		else
			cur -= v[i];

		ans = max(cur, ans);
	}

	cur = 0;

	reverse(s.begin(), s.end());
	reverse(v.begin(), v.end());

	for (int i = 0; i < s.size(); i++)
		if (s[i] == 'B')
			cur += v[i];

	for (int i = 0; i < v.size(); i++)
	{
		if (s[i] == 'A')
			cur += v[i];
		else
			cur -= v[i];

		ans = max(cur, ans);
	}

	cout << ans;

	return 0;
}


#define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#include <iostream>
#include <utility>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <climits>
#include <cstring>
#include <cmath>
#include <queue>
#include <functional>
#include <cstdio>
#include <cassert>
#include <stack>
#include <ctime>

#define mp make_pair
#define mt(x,y,z) mp((x), mp((y), (z)))
#define ZERO(x) memset((x), 0, sizeof(x))
#define NEGATE(x) memset((x), 255, sizeof(x))
using namespace std;

typedef long long ll;

int main()
{
#ifdef XXX
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

	ll n;
	scanf("%lld", &n);
	vector<ll> v(n);
	for (int i = 0; i < n; i++)
		scanf("%lld", &v[i]);

	string s;
	cin >> s;
	ll cur = 0;

	reverse(s.begin(), s.end());
	reverse(v.begin(), v.end());

	for (int i = 0; i < s.size(); i++)
		if (s[i] == 'B')
			cur += v[i];

	ll ans = cur;

	for (int i = 0; i < v.size(); i++)
	{
		if (s[i] == 'A')
			cur += v[i];
		else
			cur -= v[i];

		ans = max(cur, ans);
	}

	cout << ans;

	return 0;
}


#include <iomanip>
#include <iostream>
#include <functional>
#include <algorithm>
#include <math.h>
#include <cmath>
#include <string>
using namespace std;

int main(){
	int n;

	int p[500000];long long g = 0, h = 0, j = 0, k = 0, ot = 0;
	long long c[500000];
	cin >> n;
	for (int i = 0; i < n; i++)cin >> p[i];
	char a;
	for (int i = 0; i < n; i++){
		cin >> a;
		if (a == 'A')c[i] = -1;
		else {
			c[i] = 1;
			ot += p[i];
		}
	}
	h = ot; g = ot;
	k = ot; j = ot;
	for (int i = 0; i < n; i++){

			g =g-c[i]* p[i];
			if (h < g)h = g;
			//cout << "g" << g << "\n";
			j= j - c[n-1-i] * p[n-1-i];
			if (k < j)k = j;
			//cout << "J" << j << "\n";

	}

	cout << max(k, h);

}


#include <iostream>
#include <algorithm>
using namespace std;

char t;
long long n, p[500005], sum1[500005], sum2[500005], ans;

long long getinvsum(int ind)
{
	return max(sum2[n] - sum2[ind] + sum1[ind], sum1[n] - sum1[ind - 1] + sum2[ind - 1]);
}

int main()
{
	cin >> n;
	for (int i = 1; i <= n; i++)
		cin >> p[i];
	for (int i = 1; i <= n; i++)
	{
		cin >> t;
		sum1[i] += p[i] * (t == 'A') + sum1[i - 1];
		sum2[i] += p[i] * (t == 'B') + sum2[i - 1];
	}
	ans = sum2[n];
	for (int i = 1; i <= n; i++)
		ans = max(ans, getinvsum(i));
	cout << ans;

	return 0;
}


#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<iomanip>
#include<set>
#include<map>
#include<string>
#include<cstring>
using namespace std;
const int MM = 100000+50;
int num[MM];
string str[5];
int main ()
{
	int n;
	__int64 sum, temp;
	int i;
	while(cin>>n)
	{
		for(i = 0; i < n; i++)
			cin>>num[i];
		cin>>str[0];
		for(i = 0; i < 5; i++)
			str[i] = str[0];
		sum = 0;

		for(i = 0; i < n; i++)
			if(str[0][i] == 'B')
				sum+=num[i];
		for(i = 0; i < n && str[1][i] == 'A'; i++)
			str[1][i] = 'B';
		temp = 0;
		for(i = 0; i < n; i++)
			if(str[1][i] == 'B')
				temp+=num[i];
		sum = max(sum,temp);
		for(i = n-1; i >= 0 && str[2][i] == 'A'; i--)
			str[2][i] = 'B';
		temp = 0;
		for(i = 0; i < n; i++)
			if(str[2][i] == 'B')
				temp+=num[i];
		sum = max(sum,temp);

	}
	return 0;
}


#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<iomanip>
#include<set>
#include<map>
#include<string>
#include<cstring>
using namespace std;
const int MM = 100000+50;
int num[MM];
string str[5];
int main ()
{
	int n;
	__int64 sum, temp;
	int i;
	while(cin>>n)
	{
		for(i = 0; i < n; i++)
			cin>>num[i];
		cin>>str[0];
		for(i = 0; i < 5; i++)
			str[i] = str[0];
		sum = 0;

		for(i = 0; i < n; i++)
			if(str[0][i] == 'B')
				sum+=num[i];
		for(i = 0; i < n && str[1][i] == 'A'; i++)
			str[1][i] = 'B';
		temp = 0;
		for(i = 0; i < n; i++)
			if(str[1][i] == 'B')
				temp+=num[i];
		sum = max(sum,temp);
		for(i = n-1; i >= 0 && str[2][i] == 'A'; i--)
			str[2][i] = 'B';
		temp = 0;
		for(i = 0; i < n; i++)
			if(str[2][i] == 'B')
				temp+=num[i];
		sum = max(sum,temp);
		printf("%I64d\n", sum);
	}
	return 0;
}


#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<iomanip>
#include<set>
#include<map>
#include<string>
#include<cstring>
using namespace std;
const int MM = 5*100000+50;
int num[MM];
string str;
int main ()
{
	int n;
	__int64 sum;
	__int64 temp, Max, ans;
	int i;
	while(cin>>n)
	{
		for(i = 0; i < n; i++)
			cin>>num[i];
		cin>>str;
		sum = 0;
		for(i = 0; i < n; i++)
			if(str[i] ==  'B')
				sum += num[i];
		temp = 0;
		Max = 0;
		for(i = 0; i < n; i++)
		{
			if(str[i] == 'A')
				temp+=num[i];
			else
				temp-=num[i];
			Max = max(temp,Max);
		}
		ans = 0;
		temp = 0;
		for(i = n-1; i >= 0; i--)
		{
			if(str[i] == 'A')
				temp+=num[i];
			else
				temp-=num[i];
			ans = max(temp,ans);
		}
		Max = max(Max,ans);
		cout<<sum+Max<<endl;
	}
	return 0;
}


#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<iomanip>
#include<set>
#include<map>
#include<string>
#include<cstring>
using namespace std;
const int MM = 100000+50;
int num[MM];
string str[5];
int main ()
{
	int n;
	__int64 sum, temp;
	int i;
	while(cin>>n)
	{
		for(i = 0; i < n; i++)
			cin>>num[i];
		cin>>str[0];
		for(i = 0; i < 5; i++)
			str[i] = str[0];
		sum = 0;

		for(i = 0; i < n; i++)
			if(str[0][i] == 'B')
				sum+=num[i];
		for(i = 0; i < n && str[1][i] == 'B'; i++)
			str[1][i] = 'A';
		for(i = 0; i < n && str[1][i] == 'A'; i++)
			str[1][i] = 'B';
		temp = 0;
		for(i = 0; i < n; i++)
			if(str[1][i] == 'B')
				temp+=num[i];
		sum = max(sum,temp);
		for(i = n-1; i >= 0 && str[2][i] == 'B'; i--)
			str[2][i] = 'A';
		for(i = n-1; i >= 0 && str[2][i] == 'A'; i--)
			str[2][i] = 'B';
		temp = 0;
		for(i = 0; i < n; i++)
			if(str[2][i] == 'B')
				temp+=num[i];
		sum = max(sum,temp);
		cout<<sum<<endl;
	}
	return 0;
}


#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<iomanip>
#include<set>
#include<map>
#include<string>
#include<cstring>
using namespace std;
const int MM = 100000+50;
int num[MM];
string str[5];
int main ()
{
	int n;
	__int64 sum, temp;
	int i;
	while(cin>>n)
	{
		for(i = 0; i < n; i++)
			cin>>num[i];
		cin>>str[0];
		for(i = 0; i < 5; i++)
			str[i] = str[0];
		sum = 0;

		for(i = 0; i < n; i++)
			if(str[0][i] == 'B')
				sum+=num[i];
		for(i = 0; i < n && str[1][i] == 'A'; i++)
			str[1][i] = 'B';
		temp = 0;
		for(i = 0; i < n; i++)
			if(str[1][i] == 'B')
				temp+=num[i];
		sum = max(sum,temp);
		for(i = n-1; i >= 0 && str[2][i] == 'A'; i--)
			str[2][i] = 'B';
		temp = 0;
		for(i = 0; i < n; i++)
			if(str[2][i] == 'B')
				temp+=num[i];
		sum = max(sum,temp);
		cout<<sum<<endl;
	}
	return 0;
}


#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<iomanip>
#include<set>
#include<map>
#include<string>
#include<cstring>
using namespace std;
const int MM = 100000+50;
int num[MM];
string str;
int main ()
{
	int n;
	__int64 sum;
	__int64 temp, Max, ans;
	int i;
	while(cin>>n)
	{
		for(i = 0; i < n; i++)
			cin>>num[i];
		cin>>str;
		sum = 0;
		for(i = 0; i < n; i++)
			if(str[i] ==  'B')
				sum += num[i];
		temp = 0;
		Max = 0;
		for(i = 0; i < n; i++)
		{
			if(str[i] == 'A')
				temp+=num[i];
			else
				temp-=num[i];
			Max = max(temp,Max);
		}
		ans = 0;
		temp = 0;
		for(i = n-1; i >= 0; i--)
		{
			if(str[i] == 'A')
				temp+=num[i];
			else
				temp-=num[i];
			ans = max(temp,ans);
		}
		Max = max(Max,ans);
		cout<<sum+Max<<endl;
	}
	return 0;
}


#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
using namespace std;
long long store[1000000];
string name;
int main()
{
	long long n,i;
	cin>>n;
	for(int i=0;i<n;i++)
	{
		scanf("%lld",&store[i]);
	}
	string name;
	cin>>name;
	long long sum=0;
	for(int i=0;i<name.size();i++)
	{
		if(name[i]=='B')
			sum=sum+store[i];

	}
	long long temp=sum;
	long long ma=sum;
	for(int i=0;i<name.size();i++)
	{
		if(name[i]=='B')
			temp=temp-store[i];
		else
			temp=temp+store[i];
		ma=max(ma,temp);

	}
	temp=sum;
	for(i=name.size()-1;i>=0;i--)
	{
		if(name[i]=='B')
			temp=temp-store[i];
		else
			temp=temp+store[i];
		ma=max(ma,temp);

	}
	cout<<ma<<"\n";

}


#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <string>
#include <set>
#include <limits>
#include <iomanip>

using namespace std;

int main()  {
	int n; cin >> n;
	vector<long long> a(n);

	for( int i = 0; i < n; i++ )
		cin >> a[i];

	string s;
	cin >> s;

	vector<long long> n_l(n);
	long long prev = 0;
	for( int i = 0; i < n; i++ ) {
		prev +=a[i]*(int(s[i])-65);
		n_l[i] = prev;
	}
	vector<long long> rev(n);
	prev = 0;
	for( int i = 0; i < n; i++ ) {
		prev +=a[i]*(1-(int(s[i])-65));
		rev[i] = prev;
	}
	long long ans = n_l[n-1];
	for( int i = 0; i < n; i++ ) {
		long long t = rev[i] + n_l[n-1] - n_l[i];
		ans = max(ans,t);
	}
	for( int i = n-2; i >= 0; i-- ) {
		long long t = n_l[i] - rev[i] + rev[n-1];
		ans = max(ans,t);
	}

	cout << ans;

	return 0;
}


#define _CRT_SECURE_NO_WARNINGS

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {

	ios_base::sync_with_stdio(0);

	long long n;
	cin >> n;

	long long* dp = (long long*)malloc(n* sizeof(long long));

	for (int i = 0; i < n; ++i){
		cin >> dp[i];
	}
	string s; cin >> s;

	long long summ1 = 0, summ2 = 0;
	long long ss1 = 0, ss2 = 0;

	for (long long i = 0; i < n; ++i){
		if (s[i] == 'B') summ1 += dp[i];
	}
	ss1 = ss2 = summ2 = summ1;

	for (long long i = 0; i < n; ++i){
		if (s[i] == 'A') summ1 += dp[i];
		else summ1 -= dp[i];

		ss1 = max(ss1, summ1);
	}

	for (long long i = n - 1; i >= 0; --i){
		if (s[i] == 'A') summ2 += dp[i];
		else summ2 -= dp[i];

		ss2 = max(ss2, summ2);
	}

	cout << (max(ss1, ss2));

	free(dp);

	return 0;
}


#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <climits>
#include <cstring>

using namespace std;

#define mp make_pair
#define pp push_back
#define Sort(x) sort(x.begin(), x.end())
#define rep(i, x, y) for(int i = x; i < y; ++i)
#define Rep(i, x, y) for(int i = x; i <= y; ++i)
#define dRep(i, x, y) for(int i = x;i >= y; --i)
#define vi vector<int>
#define vvi vector<vector<int> >
#define ll long long
#define all(v) v.begin(),v.end()
#define ii pair<int, int>
#define mem(x, v) memset(x, v, sizeof(x))
#define nl '\n'
#define MOD 1000000007
#define readFile freopen("input.in", "r", stdin)

int pieces;
vi strength;
string assignment;
ll curSum;
ll maxi;

int main()
{
	while(cin >> pieces)
	{
		curSum = 0;
		strength.resize(pieces);
		rep(i, 0, pieces)
			cin >> strength[i];
		cin >> assignment;
		rep(i, 0, assignment.size())
		{
			if(assignment[i] == 'B')
				curSum += strength[i];
		}
		maxi = curSum;
		ll temp = curSum;
		rep(i, 0, assignment.size())
		{
			if(assignment[i] == 'B')
				temp -= strength[i];
			else
				temp += strength[i];
			maxi = max(maxi, temp);
		}

		temp = curSum;
		dRep(i, assignment.size() - 1, 0)
		{
			if(assignment[i] == 'B')
				temp -= strength[i];
			else
				temp += strength[i];
			maxi = max(maxi, temp);
		}

		cout << maxi << nl;
	}

	return 0;
}


#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <iomanip>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <set>
#include <map>
#include <numeric>
#include <queue>
#include <math.h>

#define forn(i, n) for (int i = 0; i < int(n); i++)
#define fore(i, l, r) for (int i = int(l); i < int(r); i++)
#define all(a) a.begin(), a.end()
#define mp make_pair
#define pb(a) push_back(a)
#define sz(a) int(a.size())
#define ft first
#define sc second
#define l_b lower_bound
#define u_b upper_bound
#define min_el min_element
#define max_el max_element

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<double, double> pdd;
typedef pair<ld, ld> pld;

int GCD(int a, int b) {
	if (a < b)
		swap(a, b);
	a %= b;
	if (a == 0)
		return b;
	else return GCD(a, b);
}

const int INF = 1000000000;
const ll INF64 = 1e18;
const int N = 2020;
const int M = 2000;
const int MOD = 1000000007;

int main() {
#ifdef _DEBUG
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
	int n;
	cin >> n;
	vector<ll> a(n);
	forn(i, n)
		scanf("%I64d", &a[i]);
	string s;
	cin >> s;

	ll start_b = 0;
	forn(i, n)
		if (s[i] == 'B')
			start_b += a[i];

	ll cur = 0;
	ll res = 0;
	forn(i, n) {
		if (s[i] == 'A')
			cur += a[i];
		else cur -= a[i];
		res = max(res, cur);
	}

	cur = 0;
	for (int i = n - 1; i >= 0; i--) {
		if (s[i] == 'A')
			cur += a[i];
		else cur -= a[i];
		res = max(res, cur);
	}

	ll result = start_b + res;
	cout << result << endl;
}


#include <iostream>
int n, strength[500000], isBstring[500000];
char buf[500000];
using namespace std;
int main()
{
	long long sum = 0, maxv = 0;

	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> strength[i];
	cin >> buf;
	for (int i = 0; i < n; i++)
	{
		if (buf[i] == 'B')
			sum += strength[i];
	}
	maxv = sum;

	// prefix
	long long tmp = sum;
	for (int i = 0; i < n; i++)
	{
		if (buf[i] == 'A')
		{
			tmp += strength[i];
		}
		else
		{
			tmp -= strength[i];
		}
		if (maxv < tmp)
			maxv = tmp;
	}

	tmp = sum;
	for (int i = n-1; i >= 0; i--)
	{
		if (buf[i] == 'A')
		{
			tmp += strength[i];
		}
		else
		{
			tmp -= strength[i];
		}
		if (maxv < tmp)
			maxv = tmp;
	}

	cout << maxv << endl;

	return 0;
}


//CPP test project
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <string>
#include <cstring>
#include <string.h>
#include <iostream>
#include <ctime>
#include <random>
#include <algorithm>
#include <vector>
#include <stack>
#include <set>
#include <map>
#include <queue>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef double db;

ll n, r, r0, res;
ll f[500100], a[500100];
char c[500100];

int main()
{
	cin >> n;
	for (int i = 0; i < n; ++i){
		cin >> f[i];
	}
	cin >> c;
	for (int i = 0; i < n; ++i){
		if (c[i] == 'B')
			r += f[i];
	}
	r0 = r;
	res = r0;
	for (int i = 0; i < n; ++i){
		if (c[i] == 'B')
			r -= f[i];
		else{
			r += f[i];
		}
		res = max(r, res);
	}
	r = r0;
	for (int i = n-1; i >= 0; --i){
		if (c[i] == 'B')
			r -= f[i];
		else{
			r += f[i];
		}
		res = max(r, res);
	}

	cout << res;
	return 0;
}


#include <iostream>
#include <stdio.h>
#include <numeric>
#include <queue>
#include <string>
#include <cmath>
#include <vector>
#include <deque>
#include <iomanip>
#include <set>
#include <queue>
#include <bitset>
#include <iomanip>
#include <map>
#include <string.h>
#include <stack>
#include <algorithm>

#include <unordered_map>
#include <unordered_set>

using namespace std;

long long p[500010];
char str[500010];

long long value_A_1[500010] , value_B_1[500010];
long long value_A_2[500010] , value_B_2[500010];

int main()
{
	int i , j , n;
	while (scanf("%d" , &n) != EOF)
	{
		memset(value_A_1 , 0 , sizeof(value_A_1));
		memset(value_A_2 , 0 , sizeof(value_A_2));
		memset(value_B_1 , 0 , sizeof(value_B_1));
		memset(value_B_2 , 0 , sizeof(value_B_2));

		for (i = 0;i < n;i ++)
			scanf("%I64d" , &p[i]);
		scanf("%s" , str);
		long long cnt1 = 0 , cnt2 = 0;
		for (i = 0;i < n;i ++)
		{
			if (str[i] == 'A')
				cnt1 += p[i];
			else
				cnt2 += p[i];
			value_A_1[i] = cnt1;
			value_B_1[i] = cnt2;
		}
		cnt1 = cnt2 = 0;
		for (i = n - 1;i >= 0;i --)
		{
			if (str[i] == 'A')
				cnt1 += p[i];
			else
				cnt2 += p[i];
			value_A_2[i] = cnt1;
			value_B_2[i] = cnt2;
		}
		long long ans = value_B_1[n - 1];
		// flip 0 to i
		for (i = 0;i < n;i ++)
		{
			long long temp = value_A_1[i];
			if (i + 1 < n)
				temp += value_B_2[i + 1];
			if (temp > ans)
				ans = temp;
		}
		for (i = n - 1;i >= 0;i --)
		{
			long long temp = value_A_2[i];
			if (i - 1 >= 0)
				temp += value_B_1[i - 1];
			if (temp > ans)
				ans = temp;
		}
		printf("%I64d\n" , ans);
	}
	return 0;
}


#include<stdio.h>
#include<string.h>
#define N 550000
int a[N][2];

int main()
{
	int n;
	while(~scanf("%d",&n))
	{
		char c;
		long long l,r;
		long long nr,nl;
		l=r=0;
		nr=nl=-1000000000000;
		for(int i=0;i<n;i++)
		{
			scanf("%d",&a[i][1]);
		}
		getchar();
		long long res=0;
		for(int i=0;i<n;i++)
		{
			scanf("%c",&c);
			if(c=='B')
			{
				res+=(long long)a[i][1];
				l-=(long long)a[i][1];
			}
			else
			{
				l+=(long long)a[i][1];
			}
			if(nl<l)nl=l;
			a[i][0]=(int)c;
		}
		for(int i=n-1;i>=0;i--)
		{
			if(a[i][0]==66)
			{
				r-=(long long)a[i][1];
			}
			else
			{
				r+=(long long)a[i][1];
			}
			if(nr<r)nr=r;
		}
		if(nr>=0 || nl>=0)
		{
			if(nl>nr)res+=nl;
			else res+=nr;
		}

		printf("%I64d\n",res);
	}
	return 0;
}


#include<stdio.h>
#include<string.h>
#define N 550000
int a[N][2];

int main()
{
	int n;
	while(~scanf("%d",&n))
	{
		char c;
		for(int i=0;i<n;i++)
		{
			scanf("%d",&a[i][1]);
		}
		getchar();
		long long res=0;
		for(int i=0;i<n;i++)
		{
			scanf("%c",&c);
			if(c=='B')res+=(long long)a[i][1];
			a[i][0]=c;
		}
		int l,r;
		long long nr,nl;
		l=r=0;
		nr=nl=0;

		for(int i=0;i<n;i++)
		{
			if(a[i][0]==66)break;
			nr+=(long long)a[i][1];
		}
		for(int i=n-1;i>=0;i--)
		{
			if(a[i][0]==66)break;
			nl+=(long long)a[i][1];
		}
		if(nl>nr)res+=nl;
		else res+=nr;
		printf("%I64d\n",res);
	}
	return 0;
}


//#include "stdafx.h"
#include <cstdio>
#include <set>
#include <string>
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
	ios_base::sync_with_stdio(false);
	int n, ind, f = 0;
	cin >> n;

	vector <long long> c1;
	c1.resize(n);
	vector <long long> c2;
	c2.resize(n);
	vector <long long> c;
	c.resize(n);
	long long m = 0;
	vector <char> s;
	s.resize(n);
	vector <long long> h1;
	h1.resize(n);
	vector <long long> h2;
	h2.resize(n);

	for (int i = 0; i < n; i++) {
		cin >> c[i];

	}
	for (int i = 0; i < n; i++) {
		cin >> s[i];
	}
	if (s[0] == 'B') h1[0] = -c[0];
	else h1[0] = c[0];
	if (h1[0] > m) {
		m = h1[0];
		ind = 0;
		f = 1;
	}

	if (s[n - 1] == 'B') h2[0] = -c[n - 1];
	else h2[0] = c[n - 1];
	if (h2[0] > m) {
		m = h2[0];
		ind = 0;
		f = 2;
	}

	if (s[0] == 'B') c1[0] = c[0];
	if (s[n - 1] == 'B') c2[0] = c[n - 1];

	for (int i = 1; i < n; i++) {

		if (s[i] == 'B') {
			h1[i] = h1[i - 1] - c[i];
			c1[i] = c1[i - 1] + c[i];
		}
		else {
			h1[i] = h1[i - 1] + c[i];
			c1[i] = c1[i - 1];
		}
		if (h1[i] > m) {
			m = h1[i];
			ind = i;
			f = 1;
		}

		if (s[n - 1 - i] == 'B') {
			h2[i] = h2[i -1] - c[n - 1 - i];
			c2[i] = c2[i - 1] + c[n - 1 - i];
		}
		else {
			h2[i] = h2[i -1] +  c[n - 1 - i];
			c2[i] = c2[i - 1];
		}
		if (h2[i] > m) {
			m = h2[i];
			ind = i;
			f = 2;
		}
	}
	if (f == 1) cout << (c1[n - 1]  + m);
	else if (f == 2) cout << (c2[n - 1] + m);
	else cout << c1[n - 1];
	return 0;
}


#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <algorithm>
typedef long long ll;
#define N 500050
#define mem(a) memset(a,0,sizeof(a))
using namespace std;
int n;
int ma[N];
char ch[N];
ll ans;
ll suma[N];
ll sumb[N];

int main()
{
    int i,j;
    while(~scanf("%d",&n)){
        for(i=0;i<n;i++)
            scanf("%d",&ma[i]);
        scanf("%s",ch);
        mem(suma);mem(sumb);
        for(i=n-1;i>=0;i--){
            suma[i]=suma[i+1];
            sumb[i]=sumb[i+1];
            if(ch[i]=='A')
                suma[i]+=ma[i];
            else sumb[i]+=ma[i];
        }
        ans=sumb[0];
        for(i=n-1;i>=0;i--){
            if(sumb[0]-sumb[i]+suma[i]>ans)
                ans=sumb[0]-sumb[i]+suma[i];
        }
        for(i=0;i<n;i++){
            if(sumb[i+1]+suma[0]-suma[i+1]>ans)
                ans=sumb[i+1]+suma[0]-suma[i+1];
        }
        printf("%I64d\n",ans);
    }
    return 0;
}


#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <algorithm>
typedef long long ll;
#define N 500050
#define mem(a) memset(a,0,sizeof(a))
using namespace std;
int n;
int ma[N];
char ch[N];
ll ans;
ll suma[N];
ll sumb[N];

int main()
{
    int i,j;
    while(~scanf("%d",&n)){
        for(i=0;i<n;i++)
            scanf("%d",&ma[i]);
        scanf("%s",ch);
        mem(suma);mem(sumb);
        for(i=n-1;i>=0;i--){
            suma[i]=suma[i+1];
            sumb[i]=sumb[i+1];
            if(ch[i]=='A')
                suma[i]+=ma[i];
            else sumb[i]+=ma[i];
        }
        ans=sumb[0];
        for(i=n-1;i>=0;i--){
            if(sumb[0]-sumb[i]+suma[i]>ans)
                ans=sumb[0]-sumb[i]+suma[i];
        }
        printf("%I64d\n",ans);
    }
    return 0;
}


#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<cstdio>
#include<numeric>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<set>
#include<map>
#include<unordered_map>
#include<unordered_set>
#include<list>
#include<cmath>
#include<bitset>
#include<cassert>
#include<queue>
#include<stack>
#include<deque>
#include<cassert>
using namespace std;
const int MAXN = 500 * 1000 + 7;
long long prefA[MAXN], prefB[MAXN], suffA[MAXN], suffB[MAXN];
int a[MAXN];
char s[MAXN];
int main()
{
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	int n;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		scanf("%d", &a[i]);
	}
	scanf("%s", s);
	for (int i = 1; i <= n; i++)
	{
		prefA[i] = prefA[i - 1];
		prefB[i] = prefB[i - 1];
		if (s[i - 1] == 'B')
		{
			prefB[i] += a[i];
		}
		else
		{
			prefA[i] -= a[i];
		}
	}
	for (int i = n; i >= 1; i--)
	{
		suffA[i] = suffA[i + 1];
		suffB[i] = suffB[i + 1];
		if (s[i - 1] == 'B')
		{
			suffB[i] += a[i];
		}
		else
		{
			suffA[i] += a[i];
		}
	}
	long long ans = prefB[n];
	for (int i = 0; i <= n + 1; i++)
	{
		ans = max(ans, prefA[i] + suffB[i + 1]);
		ans = max(ans, prefB[i] + suffA[i + 1]);
	}
	printf("%lld\n", ans);
}


#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<cstdio>
#include<numeric>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<set>
#include<map>
#include<unordered_map>
#include<unordered_set>
#include<list>
#include<cmath>
#include<bitset>
#include<cassert>
#include<queue>
#include<stack>
#include<deque>
#include<cassert>
using namespace std;
const int MAXN = 500 * 1000 + 7;
long long prefA[MAXN], prefB[MAXN], suffA[MAXN], suffB[MAXN];
int a[MAXN];
char s[MAXN];
int main()
{
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	int n;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		scanf("%d", &a[i]);
	}
	scanf("%s", s);
	for (int i = 1; i <= n; i++)
	{
		prefA[i] = prefA[i - 1];
		prefB[i] = prefB[i - 1];
		if (s[i - 1] == 'B')
		{
			prefB[i] += a[i];
		}
		else
		{
			prefA[i] += a[i];
		}
	}
	for (int i = n; i >= 1; i--)
	{
		suffA[i] = suffA[i + 1];
		suffB[i] = suffB[i + 1];
		if (s[i - 1] == 'B')
		{
			suffB[i] += a[i];
		}
		else
		{
			suffA[i] += a[i];
		}
	}
	long long ans = prefB[n];
	for (int i = 0; i <= n + 1; i++)
	{
		ans = max(ans, prefA[i] + suffB[i + 1]);
		ans = max(ans, prefB[i] + suffA[i + 1]);
	}
	printf("%lld\n", ans);
}


#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<string>
#include<iomanip>
#include<cassert>
#include<cmath>
#include<ctime>
#include<cstdlib>
using namespace std;
#define ll long long

int main() {
#ifdef LOCAL
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

	int n;
	scanf("%d", &n);
	vector<ll> p(n);
	for (int i = 0; i < n; i++)
		scanf("%d", &p[i]);
	getchar();
	for (int i = 0; i < n; i++)
		if (getchar() == 'A')
			p[i] = -p[i];
	ll sum = 0;
	for (int i = 0; i < n; i++)
		sum += (p[i] > 0) ? p[i] : 0;
	ll sum2 = sum;
	ll ans = sum;
	for (int i = 0; i < n; i++) {
		sum2 -= p[i];
		ans = max(ans, sum2);
	}
	reverse(p.begin(), p.end());
	sum2 = sum;
	for (int i = 0; i < n; i++) {
		sum2 -= p[i];
		ans = max(ans, sum2);
	}
	printf("%lld", ans);

#ifdef LOCAL
	cerr << "\ntime: " << (double)clock() / CLOCKS_PER_SEC << "\n";
#endif
	return 0;
}


#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

const int maxn = 500005;
long long a[maxn], b[maxn], k[maxn];
int main()
{
    int n;
    string s;
    while (cin >> n){
        for (int i = 1; i <= n; i++){
            cin >> k[i];
        }
        cin >> s;
        for (int i = 1; i <= n; i++){
            if (s[i - 1] == 'A'){
                a[i] = a[i - 1] + k[i];
                b[i] = b[i - 1];
            }
            else{
                b[i] = b[i - 1] + k[i];
                a[i] = a[i - 1];
            }
        }
        long long ans = 0;
        for (int i = 1; i <= n; i++){
            ans = max(ans, a[i] + b[n] - b[i]);
            ans = max(ans, b[i] + a[n] - a[i]);
        }
        cout << ans << endl;
    }
    return 0;
}


#include <iostream>
#include <algorithm>
#include <math.h>
#include <vector>
#include <set>
#include <map>
#include <iterator>
#include <string>
#include <stdio.h>
using namespace std;
typedef long long ll;
ll n, i, j,p[1000006],money,yab,best_ans,pref[1000006],suf[1000006],pref1[1000006],suf1[1000006],dl;
string s1 = "half", s2 = "halfplus",s;
int main()
{
	cin >> n;
	for (i = 0; i < n; i++)
	{
		cin >> p[i];
	}
	cin >> s;
	dl = s.length();
	if (s[0] == 'B')
	{
		pref[0] = p[0];
	}
	else
	{
		pref[0] = 0;
	}
	for (i = 1; i < dl; i++)
	{
		if (s[i] == 'B')
		{
			pref[i] = pref[i - 1] + p[i];
		}
		else
		{
			pref[i] = pref[i - 1];
		}
	}
	if (s[n - 1] == 'B')
	{
		suf[n - 1] = p[n - 1];
	}
	else
	{
		suf[n - 1] = 0;
	}

	for (i = dl - 2; i >= 0; i--)
	{
		if (s[i] == 'B')
		{
			suf[i] = suf[i + 1] + p[i];
		}
		else
		{
			suf[i] = suf[i + 1];
		}
	}
	if (s[0] == 'A')
	{
		pref1[0] = p[0];
	}
	else
	{
		pref1[0] = 0;
	}
	for (i = 1; i < dl; i++)
	{
		if (s[i] == 'A')
		{
			pref1[i] = pref1[i - 1] + p[i];
		}
		else
		{
			pref1[i] = pref1[i - 1];
		}
	}
	if (s[n - 1] == 'A')
	{
		suf1[n - 1] = p[n - 1];
	}
	else
	{
		suf1[n - 1] = 0;
	}
	for (i = dl - 2; i >= 0; i--)
	{
		if (s[i] == 'A')
		{
			suf1[i] = suf1[i + 1] + p[i];
		}
		else
		{
			suf1[i] = suf1[i + 1];
		}
	}
	best_ans = pref[n - 1];
	for (i = 0; i < n-1; i++)
	{
		best_ans = max(best_ans, pref1[i] + suf[i + 1]);
	}
	best_ans = max(best_ans, pref1[n - 1]);
	best_ans = max(best_ans, suf1[0]);
	for (i = 1; i < n; i++)
	{
		best_ans = max(best_ans, suf1[i] + pref[i - 1]);
	}
	cout << best_ans;
}


n = int(input())
prices = list(map(int, input().split()))
who = input()
basic = 0
for i in range(len(who)):
    if who[i] == "B":
        basic += prices[i]
max = basic
now = basic
for i in range(len(who)):
    if who[i] == "A":
        now += prices[i]
    else:
        now -= prices[i]
    if now > max:
        max = now
now = basic
for i in range(len(who) - 1, -1, -1):
    if who[i] == "A":
        now += prices[i]
    else:
        now -= prices[i]
    if now > max:
        max = now
print(max)


#import sys
#sys.stdin = open('in', 'r')
n = int(input())
p = [int(x) for x in input().split()]
#n,m = map(int, input().split())
s = input()
initB = 0
lmax = 0
rmax = 0

curdifl = 0
curdifr = 0
for i in range(n):
    initB += p[i] if s[i] == 'B' else 0
    curdifl += p[i] if s[i] == 'A' else -p[i]
    if curdifl > lmax:
        lmax = curdifl
    curdifr += p[-i-1] if s[-i-1] == 'A' else -p[-i-1]
    if curdifr > rmax:
        rmax = curdifr

print (initB + (max(lmax, rmax) if lmax > 0 or rmax > 0 else 0))


from sys import stdin
import operator

N = int(stdin.readline())

p = list(map(int, stdin.readline().strip().split(" ")))
teams = list(map(lambda x: 1 if x == "B" else -1, stdin.readline().strip()))

values = list(map(operator.mul, p, teams))

start = sum(filter(lambda x: max(x, 0), values))
# print(start)

total = start
best = start
for i in values:
	total -= i
	best = max(total, best)

total = start
for i in reversed(values):
	total -= i
	best = max(total, best)

# print(p, teams, values, best)
print(best)


n = input()
s = [int(x) for x in input().split(' ')]
g = input()
A = 0
B = 0
for i in range(len(g)):
    if g[i] == 'A':
        A += s[i]
    else:
        B += s[i]

startA, startB = A, B
maximum = B

for i in range(len(g)):
    if g[i] == 'A':
        A -= s[i]
        B += s[i]
    else:
        A += s[i]
        B -= s[i]
    if B > maximum:
        maximum = B

A, B = startA, startB

for i in reversed(range(len(g))):
    if g[i] == 'A':
        A -= s[i]
        B += s[i]
    else:
        A += s[i]
        B -= s[i]
    if B > maximum:
        maximum = B

print(maximum)


def main():
	n = int(input())
	ps = (int(x) for x in input().split())
	s = input()
	print(solver(ps, s))

def solver(ps, s):
	bestDScore = 0
	#bestPrefix = 0
	dScore = 0
	for i in range(len(s)):
		if s[i] == 'A':
			dScore += ps[i]
			if dScore > bestDScore:
				bestDScore = dScore
		elif s[i] == 'B':
			dScore -= ps[i]
		else:
			assert(False)

	dScore = 0
	for i in range(len(s) - 1, -1, -1):
		if s[i] == 'A':
			dScore += ps[i]
			if dScore > bestDScore:
				bestDScore = dScore
		elif s[i] == 'B':
			dScore -= ps[i]
		else:
			assert(False)
	bestScore = calculateScore(ps, s) + bestDScore
	return bestScore

def calculateScore(ps, s):
	score = 0
	for i in range(len(s)):
		if s[i] == 'B':
			score += ps[i]
	return score

main()
#L1 = [1, 2, 3, 4, 5]
#L2 = 'ABABA'
#print(solver(L1, L2))

# L3 = [1, 2, 3, 4, 5]
# L4 = 'AAAAA'
# print(solver(L3, L4))

# L3 = [1, 2, 3, 4, 5]
# L4 = 'AAAAA'
# print(solver(L3, L4))


def main():
	n = int(input())
	ps = [int(x) for x in input().split()]
	s = input()
	print(solver(ps, s))

def solver(ps, s):
	bestDScore = 0
	#bestPrefix = 0
	dScore = 0
	for i in range(len(s)):
		if s[i] == 'A':
			dScore += ps[i]
			if dScore > bestDScore:
				bestDScore = dScore
		elif s[i] == 'B':
			dScore -= ps[i]
		else:
			assert(False)

	dScore = 0
	for i in range(len(s) - 1, -1, -1):
		if s[i] == 'A':
			dScore += ps[i]
			if dScore > bestDScore:
				bestDScore = dScore
		elif s[i] == 'B':
			dScore -= ps[i]
		else:
			assert(False)
	bestScore = calculateScore(ps, s) + bestDScore
	return bestScore

def calculateScore(ps, s):
	score = 0
	for i in range(len(s)):
		if s[i] == 'B':
			score += ps[i]
	return score

main()
#L1 = [1, 2, 3, 4, 5]
#L2 = 'ABABA'
#print(solver(L1, L2))

# L3 = [1, 2, 3, 4, 5]
# L4 = 'AAAAA'
# print(solver(L3, L4))

# L3 = [1, 2, 3, 4, 5]
# L4 = 'AAAAA'
# print(solver(L3, L4))


n = int(input())
P = list(map(int, input().split()))
S = list(input())
a_sum = 0
b_sum = 0
for i in range(n):
    if S[i] == 'A':
        a_sum += P[i]
    else:
        b_sum += P[i]

max_b = b_sum
b_sum_copy = b_sum
for i in range(n):
    if S[i] == 'A':
        b_sum += P[i]
    else:
        b_sum -= P[i]
    max_b = max(max_b, b_sum)

b_sum = b_sum_copy
for i in range(n-1,-1,-1):
    if S[i] == 'A':
        b_sum += P[i]
    else:
        b_sum -= P[i]
    max_b = max(max_b, b_sum)
print(max_b)


n = int(input())
A = list(map(int, input().split()))
s = input()
val = 0
for i,c in enumerate(s):
    if c == 'B':
        val += A[i]
        A[i] = -1

subarray_val = val
max_val = val
for i in range(n+1):
    if i < n and A[i] + subarray_val > subarray_val:
        subarray_val += A[i]
    else:
        max_val = max(max_val, subarray_val)
        subarray_val = val
print(max_val)


n = int(input())
pi = list(map(int,input().split()))
ab = input()

numi = [0]*n
numi2 = [0]*n
if ab[0] == "B":
    numi[0] = pi[0]
else:
    numi2[0] = pi[0]

for i in range(1,n):
    if ab[i] == "B":
        numi[i] = numi[i-1] + pi[i]
        numi2[i] = numi2[i-1]
    else:
        numi2[i] = numi2[i-1] + pi[i]
        numi[i] = numi[i-1]
n2 = n-1
maxi = numi[n2]
for i in range(n):
    maxi = max(maxi,numi[n2] - numi[i] + numi2[i])
for i in range(n-2,-1,-1):
    maxi = max(maxi,numi[i] + numi2[n2] - numi2[i])
print(maxi)


n = int(input())
p = list(map(int, input().split()))
l = input()
change = 0
max_change = 0
init_str = 0
for i in range(len(l)):
    if l[i] == 'A':
        change += p[i]
    else:
        change -= p[i]
        init_str += p[i]
    if max_change < change:
        max_change = change
max_change_back = 0
change = 0
for i in range(len(l) - 1, -1, -1):
    if l[i] == 'A':
        change += p[i]
    else:
        change -= p[i]
    if max_change_back < change:
        max_change_back = change
print(max(max_change_back, max_change) + init_str)


def cnt(step):
    temp_total, ans = total, 0
    for i in range(N)[::step]:
        if chars[i] == 'A':
            temp_total += strengths[i]
        else:
            temp_total -= strengths[i]
        ans = max(temp_total, ans)
    return ans

N = int(input())
strengths = [int(_) for _ in input().split()]
chars = list(input())

total = 0
for i, c in enumerate(chars):
    if c == 'B':
        total += strengths[i]

print(max([total, cnt(1), cnt(-1)]))


class CodeforcesTask632BSolution:
    def __init__(self):
        self.result = ''
        self.n = 0
        self.strengths = []
        self.teams = ''

    def read_input(self):
        self.n = int(input())
        self.strengths = [int(x) for x in input().split(" ")]
        self.teams = input()

    def process_task(self):
        a_score = 0
        b_score = 0
        for x in range(self.n):
            if self.teams[x] == "A":
                a_score += self.strengths[x]
            else:
                b_score += self.strengths[x]
        mx_chng = 0
        res = 0
        resback = 0
        for for_mv in range(self.n):
            if self.teams[for_mv] == "A":
                res += self.strengths[for_mv]
            else:
                res -= self.strengths[for_mv]
            mx_chng = max(mx_chng, res)
        for back_mv in range(self.n - 1, 0, -1):
            if self.teams[back_mv] == "A":
                resback += self.strengths[back_mv]
            else:
                resback -= self.strengths[back_mv]
            mx_chng = max(mx_chng, resback)
        self.result = str(mx_chng + b_score)

    def get_result(self):
        return self.result

if __name__ == "__main__":
    Solution = CodeforcesTask632BSolution()
    Solution.read_input()
    Solution.process_task()
    print(Solution.get_result())


n, p = int( input() ) + 1, [0] + list( map( int, input().split() ) )
s = '_' + input()
ans = sum( p[i] for i in range(n) if s[i] == 'B' )
f1 = [0]
for i in range(1, n):
    f1.append(f1[-1] + ( 0 if s[i] == 'A' else p[i] ))
f1 += [0]
f2 = [0]
for i in reversed(range(1, n)):
    f2.append(f2[-1] + ( 0 if s[i] == 'A' else p[i] ) )
f2 += [0]
f2.reverse()
ac = 0
for i in range(1, n):
    if s[i] == 'A': ac += p[i]
    ans = max(ans, ac + f2[i + 1])
ac = 0
for i in reversed( range(1, n) ):
    if s[i] == 'A': ac += p[i]
    ans = max(ans, ac + f1[i - 1])
print(ans)


n = int(input())
A = list(map(int, input().split()))
b = input()
ans = 0
per = 0
start = 0
for i in range(n):
    if b[i] == 'B':
        start += A[i]
for i in range(n):
    if b[i] == 'A':
        per += A[i]
    else:
        per -= A[i]
    ans = max(per, ans)

per = 0
for i in range(n-1, -1,-1):
    if b[i] == 'A':
        per += A[i]
    else:
        per -= A[i]
    ans = max(per, ans)
print(start+ans)


n = int(input())
strength = list(map(int, input().split()))
pieces = input()

bob = 0

for pos, p in enumerate(pieces):
    if p == "B":
        bob += strength[pos]

best_flip = 0
cur_flip = 0

for st, p in zip(strength, pieces):
    if p == "A":
        cur_flip += st
    else:
        cur_flip -= st

    best_flip = max(best_flip, cur_flip)

cur_flip = 0
for st, p in zip(reversed(strength), reversed(pieces)):
    if p == "A":
        cur_flip += st
    else:
        cur_flip -= st

    best_flip = max(best_flip, cur_flip)

print(bob + best_flip)


power = 0

n = int(input())
powers = [ int(x) for x in (input().split(' ')) ]
alisa_move = input()

def count_power(move,powers,n):
    p = 0
    for i in range(0,n):
        if move[i] == 'B':
            p += powers[i]
    return p

p_max = count_power(alisa_move,powers,n)

move = list(alisa_move)
move1 = []
move1.extend(reversed(list(alisa_move)))

for i in range(0,n):
    if move[i] == 'A':
        move[i] = 'B'
        p_temp = count_power(move,powers,n)
        if (p_max < p_temp):
            p_max = p_temp
    elif move[i] == 'B':
        move[i] = 'A'

powers1=[]
powers1.extend(reversed(powers))

for i in range(0,n):
    if move1[i] == 'A':
        move1[i] = 'B'
        p_temp = count_power(move1,powers1,n)
        if (p_max < p_temp):
            print(move1)
            p_max = p_temp
    elif move1[i] == 'B':
        move1[i] = 'A'

print(p_max)


power = 0

n = int(input())
powers = [ int(x) for x in (input().split(' ')) ]
alisa_move = input()

def power_at(i,powers):
    p = powers[i]
    return p

move = list(alisa_move)
move1 = []
move1.extend(reversed(list(alisa_move)))

p_max = 0
for i in range(0,n):
    if move[i] == 'B':
        p_max+=power_at(i,powers)

p_temp = p_max
for i in range(0,n):
    if move[i] == 'A':
        move[i] = 'B'
        p_temp += power_at(i,powers)
        if (p_max < p_temp):
            p_max = p_temp
    elif move[i] == 'B':
        move[i] = 'A'
        p_temp -= power_at(i,powers)

powers1=[]
powers1.extend(reversed(powers))

p_temp=0
for i in range(0,n):
    if move1[i] == 'B':
        p_temp+=power_at(i,powers1)

for i in range(0,n):
    if move1[i] == 'A':
        move1[i] = 'B'
        p_temp += power_at(i,powers1)
        if (p_max < p_temp):
            p_max = p_temp
    elif move1[i] == 'B':
        move1[i] = 'A'
        p_temp -= power_at(i,powers1)

print(p_max)


power = 0

n = int(input())
powers = [ int(x) for x in (input().split(' ')) ]
alisa_move = input()

def power_at(i,powers):
    p = powers[i]
    return p

move = list(alisa_move)
move1 = []
move1.extend(reversed(list(alisa_move)))

p_max = 0
for i in range(0,n):
    if move[i] == 'B':
        p_max+=power_at(i,powers)

p_temp = p_max
for i in range(0,n):
    if move[i] == 'A':
        move[i] = 'B'
        p_temp += power_at(i,powers)
        if (p_max < p_temp):
            p_max = p_temp
    elif move[i] == 'B':
        move[i] = 'A'
        p_temp -= power_at(i,powers)

powers1=[]
powers1.extend(reversed(powers))

p_temp=0
for i in range(0,n):
    if move1[i] == 'B':
        p_temp+=power_at(i,powers)

for i in range(0,n):
    if move1[i] == 'A':
        move1[i] = 'B'
        p_temp += power_at(i,powers1)
        if (p_max < p_temp):
            p_max = p_temp
    elif move1[i] == 'B':
        move1[i] = 'A'
        p_temp -= power_at(i,powers1)

print(p_max)


power = 0

n = int(input())
powers = [ int(x) for x in (input().split(' ')) ]
alisa_move = input()

def count_power(move,powers,n):
    p = 0
    for i in range(0,n):
        if move[i] == 'B':
            p += powers[i]
    return p

p_max = count_power(alisa_move,powers,n)

move = list(alisa_move)
move1 = []
move1.extend(reversed(list(alisa_move)))

for i in range(0,n):
    if move[i] == 'A':
        move[i] = 'B'
        p_temp = count_power(move,powers,n)
        if (p_max < p_temp):
            p_max = p_temp
    elif move[i] == 'B':
        move[i] = 'A'

powers1=[]
powers1.extend(reversed(powers))

for i in range(0,n):
    if move1[i] == 'A':
        move1[i] = 'B'
        p_temp = count_power(move1,powers1,n)
        if (p_max < p_temp):
            p_max = p_temp
    elif move1[i] == 'B':
        move1[i] = 'A'

print(p_max)


#!/usr/bin/env python3

N = int(input())
arr = list(map(int, input().split()))
teams = input()

initial = sum(arr[i] for i in range(N) if teams[i] == 'B')
best = initial

# prefixes
cur = initial
for i in range(N):
    if teams[i] == 'B':
        cur -= arr[i]
    else:
        cur += arr[i]
        if cur > best:
            best = cur

# suffixes
cur = initial
for i in range(N-1, -1, -1):
    if teams[i] == 'B':
        cur -= arr[i]
    else:
        cur += arr[i]
        if cur > best:
            best = cur

print(best)


n = int(input())
p = [int(_) for _ in input().split()]
s = input()
ans = 0
for i in range(n):
    if s[i] == 'B':
        ans += p[i]
tmp = 0
mx = 0
for i in range(n):
    tmp += p[i] if s[i] == 'A' else -p[i]
    mx = max(tmp, mx)
tmp = 0
for i in range(n)[::-1]:
    tmp += p[i] if s[i] == 'A' else -p[i]
    mx = max(tmp, mx)
ans += mx
print(ans)


n = int(input())
ps = list(map(int, input().split()))
qs = input()

B = 0
for i in range(n):
    if qs[i] == 'B':
        B += ps[i]

maxi = B
b = B
for i in range(n):
    if qs[i] == 'A':
        b += ps[i]
    elif qs[i] == 'B':
        b -= ps[i]
    maxi = max(maxi, b)

b = B
for i in range(n-1, -1, -1):
    if qs[i] == 'A':
        b += ps[i]
    elif qs[i] == 'B':
        b -= ps[i]
    maxi = max(maxi, b)

print(maxi)


n = int(input())
powers = [int(n) for n in  input().split()]
marks = input()
Bob_power = sum([powers[i] for i in range(n) if marks[i] == 'B'])
max_Bob_power = Bob_power
start_Bob_power = Bob_power
for i in range(n):
    Bob_power += powers[i]*(1 if marks[i] == 'A' else -1)
    if max_Bob_power < Bob_power:
        max_Bob_power = Bob_power
Bob_power = start_Bob_power
for i in range(1, n + 1):
    Bob_power += powers[-i]*(1 if marks[-i] == 'A' else -1)
    if max_Bob_power < Bob_power:
        max_Bob_power = Bob_power
print(max_Bob_power)


n = int(input())
power = list(map(int, input().split()))
s = input()
cnt = 0
for i in range(n):
    if s[i] == 'B':
        cnt += power[i]
ans = cnt
k = cnt
for i in range(n):
    if s[i] == 'B':
        k -= power[i]
    else:
        k += power[i]
    ans = max(ans, k)

k = cnt
for i in range(n - 1, -1, -1):
    if s[i] == 'B':
        k -= power[i]
    else:
        k += power[i]
    ans = max(ans, k)
print(ans)


n = input()
s = [int(x) for x in input().split(' ')]
g = input()
A = 0
B = 0
for i in range(len(g)):
	if g[i] == 'A':
		A += s[i]
	else:
		B += s[i]

startA, startB = A, B
maximum = B

for i in range(len(g)):
	if g[i] == 'A':
		A -= s[i]
		B += s[i]
	else:
		A += s[i]
		B -= s[i]
	if B > maximum:
		maximum = B

A, B = startA, startB

for i in reversed(range(len(g))):
	if g[i] == 'A':
		A -= s[i]
		B += s[i]
	else:
		A += s[i]
		B -= s[i]
	if B > maximum:
		maximum = B

print(maximum)


import sys
import itertools

f = sys.stdin
g = itertools.accumulate

n = int(f.readline())
p = list(map(int, f.readline().split()))
c = f.readline()

v = [-x if y == 'B' else x for x,y in zip(p,c)]
s = sum(p[i] if c[i] == 'B' else 0 for i in range(n))
print(s+max(0, max(g(v)), max(g(v[::-1]))))


n = int(input())
p = list(map(int, input().split()))
s = input();

streng = 0;
for i in range(0, len(s)):
    if(s[i] == 'B'):
        streng += p[i]

b = 0;
a = 0;
ans = streng
for i in range(0, len(s)):
    if(s[i] == 'B'):
        b +=p[i]
    else:
        a += p[i]
    curStren = streng - b + a;
    if curStren > ans:
        ans = curStren
a =  0;
b = 0;
for i in range(1, len(s) + 1):
    if(s[-i] == 'B'):
        b +=p[-i]
    else:
        a += p[-i]
    curStren = streng - b + a;
    if curStren > ans:
        ans = curStren

print(ans)


n=int(input())
p=list(map(int,input().split()))
s=input()
maxi=0
temp=0
local=-1
for i in range(n):
    if s[i]=='A':
        temp+=p[i]
    else:
        temp-=p[i]
    if temp>maxi:
        local=i
        maxi=temp
ans=0

for i in range(local+1):
    if s[i]=='A':
        ans+=p[i]

for i in range(local+1,n):
    if s[i]=='B':
        ans+=p[i]

maxi=0
temp=0
local=-1
p=list(reversed(p))
s=s[::-1]
for i in range(n):
    if s[i]=='A':
        temp+=p[i]
    else:
        temp-=p[i]
    if temp>maxi:
        local=i
        maxi=temp
ans1=0
for i in range(local+1):
    if s[i]=='A':
        ans1+=p[i]
for i in range(local+1,n):
    if s[i]=='B':
        ans1+=p[i]

print(max(ans,ans1))


read = lambda: map(int, input().split())
n = int(input())
p = list(read())
a = [{'B': 1, 'A': 0}[i] for i in input()]
cur = sum(p[i] for i in range(n) if a[i])
ans = cur
b = a[:]
for i in range(n):
    b[i] = int(not a[i])
    if b[i]: cur += p[i]
    else: cur -= p[i]
    ans = max(ans, cur)
cur = sum(p[i] for i in range(n) if a[i])
b = a[:]
for i in range(n - 1, -1, -1):
    b[i] = int(not a[i])
    if b[i]: cur += p[i]
    else: cur -= p[i]
    ans = max(ans, cur)
print(ans)


# -*- coding: utf-8 -*-
"""
Created on Sun Mar 13 11:31:34 2016

@author: kebl4230
"""

n = int(input())
strengths = [int(num) for num in input().split()]
tmp = input()
teams = [1 if let == "B" else 0 for let in tmp]
result = 0
##
indexes = [num for num in range(n)]
for position in indexes:
    tmp = [teams[num] if num > position else ((teams[num] + 1) % 2) for num in indexes]
    bb = sum([a * b for a, b in zip(strengths, tmp)])
    result = max(result, max(bb, sum(strengths) - bb))
print(result)
5


# -*- coding: utf-8 -*-
"""
Created on Sun Mar 13 11:31:34 2016

@author: kebl4230
"""

n = int(input())
strengths = [int(num) for num in input().split()]
tmp = input()
teams = [1 if let == "B" else 0 for let in tmp]
result = 0
indexes = [num for num in range(n)]
for position in indexes:
    suffix = list(map(lambda x: ((x + 1) % 2), teams[position:n]))
    prefix = teams[0:position]
    prefix.extend(suffix)
    bb = sum([a * b for a, b in zip(strengths, prefix)])
    result = max(result, max(bb, sum(strengths) - bb))
print(result)


# -*- coding: utf-8 -*-
"""
Created on Sun Mar 13 11:31:34 2016

@author: kebl4230
"""
import itertools

g = itertools.accumulate

n = int(input())
strengths = [int(num) for num in input().split()]
teams = input()

indexes = [num for num in range(n)]
s2 = [strengths[i] if teams[i] == "B" else 0 for i in indexes]
v = [a - 2*b for a, b in zip(strengths, s2)]
b = sum(s2)
result = b + max(0, max(g(v)), max(g(v[::-1])))
print(result)


# -*- coding: utf-8 -*-
"""
Created on Sun Mar 13 11:31:34 2016

@author: kebl4230
"""
import itertools

g = itertools.accumulate

n = int(input())
strengths = [int(num) for num in input().split()]
teams = input()

indexes = [num for num in range(n)]
s2 = [strengths[i] if teams[i] == "B" else 0 for i in indexes]
v = [a - 2*b for a, b in zip(strengths, s2)]
b = sum(s2)
result = b + max(max(g(v)), max(g(v[::-1])))
print(result)


# -*- coding: utf-8 -*-
"""
Created on Sun Mar 13 11:31:34 2016

@author: kebl4230
"""
import itertools

n = int(input())
strengths = [int(num) for num in input().split()]
tmp = input()
teams = [1 if let == "B" else 0 for let in tmp]
result = 0
indexes = [num for num in range(n)]
for position in indexes:
    suffix = list(map(lambda x: ((x + 1) % 2), teams[position:n]))
    prefix = teams[0:position]
    prefix.extend(suffix)
    bb = sum(itertools.product(strengths, prefix))
    result = max(result, max(bb, sum(strengths) - bb))
print(result)

# bb = sum([a * b for a, b in zip(strengths, prefix)])


# -*- coding: utf-8 -*-
"""
Created on Sun Mar 13 11:31:34 2016

@author: kebl4230
"""

n = int(input())
strengths = [int(num) for num in input().split()]
tmp = input()
teams = [1 if let == "B" else 0 for let in tmp]
result = 0
indexes = [num for num in range(n)]
for position in indexes:
    tmp = [(strengths[num] * teams[num]) if num > position else
           (strengths[num] * ((teams[num] + 1) % 2)) for num in indexes]
    result = max(result, max(sum(tmp), sum(strengths) - sum(tmp)))
print(result)

#     bb = sum([a * b for a, b in zip(strengths, tmp)])


n = int(input())
L = list(map(int,input().split()))
s = input()

prefixe = [None for i in range(n)]
suffixe = [None for i in range(n)]
sum = 0
for i in range(n):
    if s[i] == "B":
        sum += L[i]
if s[0] == "A":
    prefixe[0] = [L[0],L[0]]
else:
    prefixe[0] = [-L[0],0]
for i in range(1,n):
    if s[i] == "A":
        if prefixe[i-1][0] + L[i] >= prefixe[i-1][1]:
            prefixe[i] = [prefixe[i-1][0] + L[i],prefixe[i-1][0] + L[i]]
        else:
            prefixe[i] = [prefixe[i-1][0] + L[i],prefixe[i-1][1]]
    else:
        prefixe[i] = [prefixe[i-1][0] - L[i], prefixe[i-1][1]]
if s[-1] == "A":
    suffixe[-1] = [L[-1],L[-1]]
else:
    suffixe[-1] = [-L[-1],0]
for i in range(n-2,-1,-1):
    if s[i] == "A":
        if suffixe[i+1][0] + L[i] >= suffixe[i+1][1]:
            suffixe[i] = [suffixe[i+1][0] + L[i],suffixe[i+1][0] + L[i]]
        else:
            suffixe[i] = [suffixe[i+1][0] + L[i], suffixe[i+1][1]]
    else:
        suffixe[i] = [suffixe[i+1][0] - L[i], suffixe[i+1][1]]
P = max([prefixe[i][1] for i in range(n)])
S = max([suffixe[i][1] for i in range(n)])
if max(P,S) > 0:
    print(max(P,S)+sum)
else:
    print(sum)


n = int(input())
L = list(map(int,input().split()))
s = input()

prefixe = [None for i in range(n)]
suffixe = [None for i in range(n)]
sumA = 0
sumB = 0
for i in range(n):
    if s[i] == "B":
        sumB += L[i]
    else:
        sumA += L[i]
sum = max(sumA,sumB)
for i in range(n):
    if s[i] == "A":
        sumA -= L[i]
        sumB += L[i]
    else:
        sumA += L[i]
        sumB -= L[i]
    sum = max(sum,max(sumA,sumB))

print(sum)


n, t = int(input()), list(map(int, input().split()))
b = [q * (d == 'B') for q, d in zip(t, input())]
v = sum(b)
u = sum(t) - v
s = max(u, v)
for i, j in zip(b, t):
    u += 2 * i - j
    v += j - 2 * i
    s = max(u, v, s)
print(s)


n, t = int(input()), list(map(int, input().split()))
b = [q * (d == 'B') for q, d in zip(t, input())]
y = v = sum(b)
x = u = sum(t) - v
for i in range(n):
    u += 2 * b[i] - t[i]
    x = max(x, u)
    v += t[i] - 2 * b[i]
    y = max(y, v)
print(max(x, y))


n, t = int(input()), list(map(int, input().split()))
b = [q * (d == 'B') for q, d in zip(t, input())]
v = sum(b)
u = sum(t) - v
s = max(u, v)
for i in range(n):
    u += 2 * b[i] - t[i]
    v += t[i] - 2 * b[i]
    s = max(u, v, s)
print(s)


n, t = int(input()), list(map(int, input().split()))

b = [q * (d == 'B') for q, d in zip(t, input())]

v = sum(b)

u = sum(t) - v

s = max(u, v)

for i, j in zip(b, t):

    u += 2 * i - j

    v += j - 2 * i

    s = max(u, v, s)

print(s)

# Made By Mostafa_Khaled


import collections
import math

#n, p = map(int, input().split())
n = int(input())
p = list(map(int, input().split()))
s = input()

def solve(p, s):
    a, b = [0] * n, [0] * n
    m = 0
    if s[0] == 'B':
        b[0] = p[0]
        m += p[0]
    else:
        a[0] = p[0]
    for i in range(1, n):
        if s[i] == 'B':
            b[i] += p[i]
            m += p[i]
        else:
            a[i] += p[i]
        a[i] += a[i - 1]
        b[i] += b[i - 1]
    ans = m
    for i in range(n):
        if m - b[i] + a[i] > ans:
            ans = m - b[i] + a[i]
    return ans
print(max(solve(p, s), solve(p[::-1], s[::-1])))


import sys
import math
# sys.stdin = open('input.txt')
# sys.stdout = open('output.txt', 'w')

def main():
    n = int(input())
    p = list(map(int, input().split()))
    s = input()
    prefa = [0] * n
    prefb = [0] * n
    for i in range(n):
        if i != 0:
            prefa[i] = prefa[i - 1]
            prefb[i] = prefb[i - 1]
        if s[i] == 'A':
            prefa[i] += p[i]
        else:
            prefb[i] += p[i]
    suffa = [0] * n
    suffb = [0] * n
    for i in reversed(range(n)):
        if i != n - 1:
            suffa[i] = suffa[i + 1]
            suffb[i] = suffb[i + 1]
        if s[i] == 'A':
            suffa[i] += p[i]
        else:
            suffb[i] += p[i]
    maxa = suffb[0]
    for i in range(n):
        t1 = prefa[i]
        if i != n - 1:
            t1 += suffb[i + 1]
        t2 = suffa[i]
        if i != 0:
            t2 += prefb[i - 1]
        maxa = max([maxa, t1, t2])
    print(maxa)

main()


n = int(input())
p = list(map(int, input().split()))
s = input()
ans = 0

cur_orig = 0
for i in range(0, len(s)):
    if s[i] == 'B': cur_orig += p[i]

cur = cur_orig
ans = cur_orig

for i in range(0, len(s)):
    if s[i] == 'A':
        cur += p[i]
        ans = max(ans, cur)
    else:
        cur -= p[i]

cur = cur_orig

for i in range(len(s) - 1, -1, -1):
    if s[i] == 'A':
        cur += p[i]
        ans = max(ans, cur)
    else:
        cur -= p[i]

print(ans)


n = int(input())
p = list(map(int, input().split()))
s = input()
ans = 0

cur_orig = 0
for i in range(0, n):
    if s[i] == 'B': cur_orig += p[i]

cur = cur_orig
ans = cur_orig

for i in range(0, n):
    if s[i] == 'A':
        cur += p[i]
        ans = max(ans, cur)
    else:
        cur -= p[i]

cur = cur_orig

for i in range(n - 1, -1, -1):
    if s[i] == 'A':
        cur += p[i]
        ans = max(ans, cur)
    else:
        cur -= p[i]

print(ans)


import sys
import itertools

f = sys.stdin
g = itertools.accumulate

n = int(f.readline())
p = list(map(int, f.readline().split()))
c = f.readline()

v = [-x if y == 'B' else x for x,y in zip(p,c)]
s = sum(p[i] if c[i] == 'B' else 0 for i in range(n))
print(s+max(0, max(g(v)), max(g(v[::-1]))))


n = int(input())
P = list(map(int, input().split()))
s = input()
res = sum(P[i] for i in range(n) if s[i] == 'B')
maxdiff = 0
suma = 0
sumb = 0
for i in range(n):
    if(s[i] == 'A'):
        suma += P[i]
    else:sumb += P[i]
    if(suma - sumb > maxdiff):
        maxdiff = suma - sumb

suma = 0
sumb = 0
for i in range(n)[::-1]:
    if(s[i] == 'A'):
        suma += P[i]
    else:sumb += P[i]
    if(suma - sumb > maxdiff):
        maxdiff = suma - sumb

print(res + maxdiff)


n=int(input())
l=[int(i) for i in input().split()]
s=list(input())
sm=0
for i in range(n):
    if s[i]=='B':
        sm+=l[i]
        l[i]=-l[i]
#print(l)
maxi1=0
sm1=0
for i in range(n):
    sm1+=l[i]
    maxi1=max(maxi1,sm1)
sm2=0
maxi2=0
for i in range(n-1,-1,-1):
    sm2+=l[i]
    maxi2=max(maxi2,sm2)
print(sm+max(maxi1,maxi2))


n=int(input())
l=[int(i) for i in input().split()]
s=list(input())
sm=0
for i in range(n):
    if s[i]=='B':
        sm+=l[i]
        l[i]=-l[i]
maxi=0
curr=0
for i in l:
    curr=max(i,curr+i)
    maxi=max(maxi,curr)
print(sm+maxi)


n=int(input())
l=[int(i) for i in input().split()]
s=list(input())
sm=0
for i in range(n):
    if s[i]=='B':
        sm+=l[i]
        l[i]=-l[i]
maxi1=0
sm1=0
for i in range(n):
    sm1+=l[i]
    maxi1=max(maxi1,sm1)
sm2=0
maxi2=0
for i in range(n-1,-1,-1):
    sm2+=l[i]
    maxi2=max(maxi2,l[i])
print(sm+max(maxi1,maxi2))


def main():
    input()
    pp = list(map(int, input().split()))
    mask = [c == 'B' for c in input()]
    s = t = sum(p for p, m in zip(pp, mask) if m)
    res = [s]
    for p, m in zip(pp, mask):
        if m:
            s -= p
        else:
            s += p
            res.append(s)
    pp.reverse()
    mask.reverse()
    for p, m in zip(pp, mask):
        if m:
            t -= p
        else:
            t += p
            res.append(t)
    print(max(res))

if __name__ == '__main__':
    main()


/*
	Anyone can start again
		Not through love, but through revenge
	Through the fire, we're born again
		Peace by vengeance, brings the end
 */
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;
template <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class T>  inline void smax(T &x,T y){ x = max((x), (y));}
template <class T>  inline void smin(T &x,T y){ x = min((x), (y));}
const int maxn = 1e5 + 100;
typedef pair<int, pii> query;
query q[maxn];
int n;
vi ts;
unordered_map<int, int> se[maxn * 4];
inline void push(int x, int y, int a, bool ins = true, int id = 1, int l = 0, int r = n){
	if(x >= r or l >= y)	return ;
	if(x <= l && r <= y){
		if(ins)
			se[id][a] ++;
		else
			se[id][a] --;
		return ;
	}
	int mid = (l + r)/2;
	if(se[id].find(a) != se[id].end() && se[id][a]){
		se[id][a] --;
		se[L(id)][a] ++;
		se[R(id)][a] ++;
	}
	if(se[id].find(a) != se[id].end() && !se[id][a])
		se[id].erase(a);
	push(x, y, a, ins, L(id), l, mid);
	push(x, y, a, ins, R(id), mid, r);
}
inline int coun(int p, int a, int id = 1, int l = 0, int r = n){
	int ans = (se[id].find(a) != se[id].end()? se[id][a]: 0);
	if(r - l < 2)	return ans;
	int mid = (l + r)/2;
	if(p < mid)
		return ans + coun(p, a, L(id), l, mid);
	return ans + coun(p, a, R(id), mid, r);
}
int main(){
	iOS;
	cin >> n;
	For(i,0,n){
		int a, t, x;
		cin >> a >> t >> x;
		q[i] = {a, {t, x}};
		ts.pb(t);
	}
	sort(all(ts));
	For(i,0,n){
		int a = q[i].x, t = q[i].y.x, x = q[i].y.y;
		t = lower_bound(all(ts), t) - ts.begin();
		if(a == 1)
			push(t, n, x);
		else if(a == 2)
			push(t, n, x, 0);
		else
			cout << coun(t, x) << '\n';
	}
	return 0;
}


/*
	Anyone can start again
		Not through love, but through revenge
	Through the fire, we're born again
		Peace by vengeance, brings the end
 */
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;
template <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class T>  inline void smax(T &x,T y){ x = max((x), (y));}
template <class T>  inline void smin(T &x,T y){ x = min((x), (y));}
const int maxn = 1e5 + 100;
typedef pair<int, pii> query;
query q[maxn];
int n;
vi ts;
unordered_multiset<int> se[maxn * 4];
inline void push(int x, int y, int a, bool ins = true, int id = 1, int l = 0, int r = n){
	if(x >= r or l >= y)	return ;
	if(x <= l && r <= y){
		if(ins)
			se[id].insert(a);
		else
			se[id].erase(se[id].find(a));
		return ;
	}
	int mid = (l + r)/2;
	if(se[id].count(a)){
		se[id].erase(se[id].find(a));
		se[L(id)].insert(a);
		se[R(id)].insert(a);
	}
	push(x, y, a, ins, L(id), l, mid);
	push(x, y, a, ins, R(id), mid, r);
}
inline int coun(int p, int a, int id = 1, int l = 0, int r = n){
	int ans = se[id].count(a);
	if(r - l < 2)	return ans;
	int mid = (l + r)/2;
	if(p < mid)
		return ans + coun(p, a, L(id), l, mid);
	return ans + coun(p, a, R(id), mid, r);
}
int main(){
	iOS;
	cin >> n;
	For(i,0,n){
		int a, t, x;
		cin >> a >> t >> x;
		q[i] = {a, {t, x}};
		ts.pb(t);
	}
	sort(all(ts));
	For(i,0,n){
		int a = q[i].x, t = q[i].y.x, x = q[i].y.y;
		t = lower_bound(all(ts), t) - ts.begin();
		if(a == 1)
			push(t, n, x);
		else if(a == 2)
			push(t, n, x, 0);
		else
			cout << coun(t, x) << '\n';
	}
	return 0;
}


/*
	Anyone can start again
		Not through love, but through revenge
	Through the fire, we're born again
		Peace by vengeance, brings the end
 */
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;
template <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class T>  inline void smax(T &x,T y){ x = max((x), (y));}
template <class T>  inline void smin(T &x,T y){ x = min((x), (y));}
const int maxn = 1e5 + 100;
typedef pair<int, pii> query;
query q[maxn];
int n;
vi ts;
multiset <int> se[maxn * 4];
inline void push(int x, int y, int a, bool ins = true, int id = 1, int l = 0, int r = n){
	if(x >= r or l >= y)	return ;
	if(x <= l && r <= y){
		if(ins)
			se[id].insert(a);
		else
			se[id].erase(se[id].find(a));
		return ;
	}
	int mid = (l + r)/2;
	if(se[id].count(a)){
		se[id].erase(se[id].find(a));
		se[L(id)].insert(a);
		se[R(id)].insert(a);
	}
	push(x, y, a, ins, L(id), l, mid);
	push(x, y, a, ins, R(id), mid, r);
}
inline int coun(int p, int a, int id = 1, int l = 0, int r = n){
	int ans = se[id].count(a);
	if(r - l < 2)	return ans;
	int mid = (l + r)/2;
	if(p < mid)
		return ans + coun(p, a, L(id), l, mid);
	return ans + coun(p, a, R(id), mid, r);
}
int main(){
	iOS;
	cin >> n;
	For(i,0,n){
		int a, t, x;
		cin >> a >> t >> x;
		q[i] = {a, {t, x}};
		ts.pb(t);
	}
	sort(all(ts));
	For(i,0,n){
		int a = q[i].x, t = q[i].y.x, x = q[i].y.y;
		t = lower_bound(all(ts), t) - ts.begin();
		if(a == 1)
			push(t, n, x);
		else if(a == 2)
			push(t, n, x, 0);
		else
			cout << coun(t, x) << '\n';
	}
	return 0;
}


#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <string>
#include <cmath>
#include <stack>
#define ll long long
#define ull unsigned long long
#define exp 0.00000001
using namespace std;
const int mxx = 1e6+5;
const int mx = 1e9+5;
map<int, int>ma[mxx];///ma[每个数字b(第几个数)][时间轴]；
map<int, int>mma;///每个数字b离散为第几个没出现的数
///树状数组模板。。。
int bit(int x)
{
    return x&(-x);
}

void up(int x, int y, int k)
{
    while (x < mx)
    {
        ma[y][x] += k;///k为1时数字进来,-1时代表出去。。。。
        x += bit(x);
    }
    return;
}

int qry(int x, int y)
{
    int ans = 0;
    while (x)
    {
        ans += ma[y][x];
        x -= bit(x);
    }
    return ans;
}
int main()
{
    int n, t, a, b, cnt = 1;
    scanf("%d", &n);
    for (int i = 0; i < n; ++i)
    {
        scanf("%d%d%d", &t, &a, &b);
        if (!mma[b] && t == 1) mma[b] = cnt++;///每种数字，这就算是简略的离散了
        if (t == 1)
            up(a, mma[b], 1);
        else if (t == 2)
            up(a, mma[b], -1);
        else printf("%d\n", qry(a, mma[b]));
    }
   return 0;
}
//hellobig_tq//hello


#include <queue>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <complex>
#include <fstream>
#include <cstring>
#include <string>
#include <climits>
using namespace std;

//macros
typedef long long ll;
typedef complex<double> point;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef vector< vector<int> > vvi;

#define FOR(k,a,b) for(int k=(a); k<=(b); ++k)
#define REP(k,a) for(int k=0; k<(a);++k)
#define SZ(a) int((a).size())
#define ALL(c) (c).begin(),(c).end()
#define PB push_back
#define MP make_pair
#define INF 1999999999
#define INFLONG 1000000000000000000
#define MOD 1000000007
#define MAX 100
#define ITERS 100
#define MAXM 200000
#define MAXN 200000
#define _gcd __gcd
#define eps 1e-9
#define PI 3.1415926535897932384626

struct query{int ty; int ti; int val;
    query(int a, int b, int c){
        ty = a;
        ti = b;
        val = c;
    }
};

vi addo[100000];
vi remo[100000];

int main() {
    ios_base::sync_with_stdio(false);
    vector<query> qs;
    vi timos;
    int n;
    cin >> n;
    REP(i,n){
        int a,b,c;
        cin >> a >> b >> c;
        query qo(a,b,c);
        qs.PB(qo);
        timos.PB(b);
    }
    sort(ALL(timos));
    map<int,int> mapo;
    REP(i,SZ(timos)){
        mapo[timos[i]] = i;
    }
    vector<query> queries;
    REP(i,SZ(qs)){
        qs[i].ti = mapo[qs[i].ti];
    }

    int ptr = 0;
    map<int,int> valo;
    map<int,bool> seen;
    REP(i,SZ(qs)){
        int vo = qs[i].val;
        if(!seen[vo]){
            seen[vo] = true;
            valo[vo] = ptr;
            ptr++;
        }
        qs[i].val = valo[vo];
    }
    /*
    REP(i,SZ(qs)){
        if(qs[i].ty==1){
            addsz[qs[i].val]++;
        }
        else if(qs[i].ty==2){
            remsz[qs[i].val]++;
        }
    }
    bool viso[100000];
    REP(i,100000) viso[i] = false;
    */
    REP(i,SZ(qs)){
        int ty = qs[i].ty;
        int ti = qs[i].ti;
        int vo = qs[i].val;
        if(ty==1){
            addo[vo].PB(ti);
        }
        else if(ty==2){
            remo[vo].PB(ti);
        }
        else if(ty==3){
            sort(ALL(addo[vo]));
            sort(ALL(remo[vo]));
            vector<int>::iterator it1 = upper_bound(ALL(addo[vo]),ti);
            --it1;
            vector<int>::iterator it2 = upper_bound(ALL(remo[vo]),ti);
            int ans = 0;
            if(it2==remo[vo].begin()){
                ans = it1 - addo[vo].begin()+1;
            }
            else{
                --it2;
                ans = (it1-addo[vo].begin()+1) - (it2-remo[vo].begin()+1);
            }
            cout << ans << "\n";
        }
    }
}