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
#include <iostream>
#include <vector>
#include <string>

long gcd(long a, long b)
{
  long c = a % b;
  while(c != 0)
  {
    a = b;
    b = c;
    c = a % b;
  }
  return b;
}

long long lcm(long a, long b)
{
    long long temp = gcd(a, b);

    return temp ? ((long long)a / temp * b) : 0;
}

long long findLooseTurnInCycle(long long cash, long position, long long cycle, const std::string& games)
{
	long long i = position;
	while (cash > 0 && i < cycle)
	{
		cash += games[ i % games.length() ] == 'W' ? 1 : -1;

		if (cash == 0)
		{ 
			break;
		}

		i += games.length();
	}
	return i;
}

int main(void)
{
	long n,m;
	std::vector<long> startCash;
	std::string games;

	std::cin >> n;
	startCash.resize(n);
	for (long i=0; i<n; i++)
	{
		std::cin >> startCash[i];
	}
	std::cin >> m >> games;
	
	std::vector<long> cashChange, minCashChange;
	cashChange.assign(n,0);
	minCashChange.assign(n,0);


	long long mnLcm = lcm(m, n);

	for (long long i=0; i<mnLcm; i++)
	{
		cashChange[i%n] += ( games[i%m] == 'W' ? 1 : -1);

		if (startCash[i%n] + cashChange[i%n] == 0)
		{
			std::cout << (i+1) << std::endl;
			return 0;
		}

		if (cashChange[i%n] < minCashChange[i%n])
		{
			minCashChange[i%n] = cashChange[i%n];
		}

	}

	long long firstLooserTurn;
	long firstLooserFullCycles;
	int firstLooser = -1;
	//select fist loosers
	for (int i=0; i<n; i++)
	{
		if (cashChange[i] < 0)
		{
			long fullCycles = ((startCash[i] + minCashChange[i]) / (-1*cashChange[i])) + ((startCash[i] + minCashChange[i]) % (-1*cashChange[i]) ? 1 : 0);
			
			if (firstLooser < 0)
			{
				firstLooser = i;
				firstLooserFullCycles = fullCycles;
				firstLooserTurn = fullCycles * mnLcm + findLooseTurnInCycle(startCash[i] + fullCycles*cashChange[i], i, mnLcm, games);
			}
			else
			{
				if (fullCycles <= firstLooserFullCycles)
				{
					long long looserTurn = fullCycles * mnLcm + findLooseTurnInCycle(startCash[i] + fullCycles*cashChange[i], i, mnLcm, games);
					if (looserTurn < firstLooserTurn)
					{
						firstLooser = i;
						firstLooserFullCycles = fullCycles;
						firstLooserTurn = looserTurn;
					}
				}
			}
		}
	}

	std::cout << (firstLooser < 0 ? -1 : (firstLooserTurn+1)) << std::endl;

	return 0;
}