1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include<iostream>
using namespace std;

int * a;
int * b;
int * c;
int * mins;

int main()
{
	int n, m;
	cin >> n;
	a = new int [n];
	int min_a=1000001;
	for(int i=0; i<n; i++)
	{
		cin >> a[i];
		if(a[i]<min_a)	min_a=a[i];
	}
	cin >> m;
	b = new int [m];
	for(int i=0; i<m; i++) 
	{
		char znak;
		cin >> znak;
		if(znak == 'W') b[i]=1;
		else b[i]=-1;
	}
	if(n%m == 0)
	{
		bool warunek=0;
		for(int i=0; i<m; i++) if(b[i] == -1) warunek = 1;
		if(!warunek) cout << -1;
		else
		{
			int minn=1000001, best;
			for(int i=0; i<n; i++) 
				if(a[i] < minn && b[i%m] == -1)
				{
					minn=a[i];
					best=i;
				}
			if(minn == 1000001) cout << "-1";
			else cout << (minn-1)*n+(best+1);
		}
	}
	else
	{
		c = new int [n+(m/n)];
		int l=0, minn=100, suma=0;
		for(int i=0; i<n+(m/n); i++) 
		{
			c[i]=b[l];
			suma+=c[i];
			if(suma < minn) minn = suma;
			l+=(n%m);
		}
		mins = new int [n];
		mins[0]=minn;
		for(int i=1; i<n; i++) mins[i]=mins[i-1]+c[n-(i%m)];
		minn = 1000001;
		bool w=1;
		int kroki, dla; ////
		for(int i=0; i<n; i++) 
		{
			if(a[i]-mins[i] <= 0)
			{ 
				int liczba=a[i];
				for(int j=0; j<n; j++)
				{
					a[i]+=c[(j+n%m)%n];
					if(a[i] <= 0)
					{
					 	kroki=j;
					 	break;
					}
				}
				if(minn > kroki+1)
				{
				 	minn=kroki+1;
				 	dla=i;
				}
				w=0;
			}	
		}
		cout << n*minn-(n-dla+1);
		if(w) 
		{
			int o_ile=min_a/suma;
			if(o_ile <= 0) cout << -1;
			else
			{
				for(int i=0; i<n; i++) a[i]-=o_ile;
				int kroki, dla;
				for(int i=0; i<n; i++) 
				{
					if(a[i]-mins[i] <= 0)
					{ 
						int liczba=a[i];
						for(int j=0; j<n; j++)
						{
							a[i]+=c[(j+n%m)%n];
							if(a[i] <= 0)
							{
							 	kroki=j;
							 	break;
							}
						}
						if(minn > kroki+1)
						{
						 	minn=kroki+1;
						 	dla=i;
						}
					}	
				}
				cout << n*minn-(n-dla+1);
			}
		}
	}
}