## Sample Input

4
2 3 2 1
3
WPP


## Sample Output

12


## 代码

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,ll> pil;
const ll N=2e6+7,INF=1e18;
struct MonotoneQueue:deque<pil>
{
void push(pil p,int k)
{
while(!empty()&&back().second>=p.second)pop_back();
for(push_back(p); p.first-front().first>=k;)pop_front();
}
};
char s[N];
ll ans=INF;
int n,m,a[N],vis[N],mn[N],sum[N],pre[N<<1];
int main()
{
scanf("%d",&n);
for(int i=0; i<n; ++i)scanf("%d",&a[i]);
scanf("%d%s",&m,s);
for(int k=0; k<m; ++k)
if(!vis[k])
{
MonotoneQueue q;
vector<int> v;
for(int i=k; !vis[i]; i=(i+n)%m)v.push_back(i),vis[i]=1;
for(int i=0; i<2*v.size(); ++i)
{
q.push(pil(i+1,sum[i+1]=sum[i]+(s[v[i%v.size()]]=='W'?1:-1)),v.size()+1);
if(i>=v.size())mn[i-v.size()+1]=sum[i-v.size()]-q.front().second;
}
for(int i=2*v.size(); pre[sum[i]+N]=i; --i)
if(i<=v.size())
for(int j=v[i-1]; j<n; j+=m)
if(sum[v.size()]<0||a[j]<=mn[i])
{
ll step;
if(a[j]<=mn[i])step=pre[sum[i-1]-a[j]+N]-i+1;
else
{
ll lop=(a[j]-mn[i]-1)/(-sum[v.size()])+1;
step=lop*v.size()+pre[sum[i-1]-a[j]-lop*sum[v.size()]+N]-i+1;
}
ans=min(ans,j+1+n*(step-1));
}
}
printf("%lld",ans<INF?ans:-1LL);
}