#include #include #include #include #include using namespace std; typedef long long llint; const int MAX = 300300; const llint inf = 1e18; int a[MAX]; map S[MAX]; // one-way map P[MAX]; // round-trip llint solve(string q, llint cA, llint cB, llint cAB, llint cBA) { int N = q.size(); if (cAB > cBA) { // make cAB <= cBA swap(cAB, cBA); swap(cA, cB); for (auto& c: q) { c ^= 'A' ^ 'B'; } } cA = min(cA, cAB); cB = min(cB, cBA); // now round-trip tickets must be used completely int cnt_A = count(q.begin(), q.end(), 'A'); int cnt_B = N - cnt_A; // 3 cases: if (cA + cB <= cAB) { return cnt_A*cA + cnt_B*cB ; } int K = 0; int next_B = 0; for (int i = 0; i < N; ++i) { if (q[i] == 'A') { while (next_B < N && (next_B < i || q[next_B] != 'B')) next_B++; if (next_B < N) { K++; next_B++; } } } // K = max. number of A-B matches, where B is after A if (cAB <= cA + cB && cA + cB <= cBA) { return K*cAB + (cnt_A - K)*cA + (cnt_B - K)*cB; } int L = min(cnt_A, cnt_B) - K; // L = max. number of B-A matches, after K A-B matches are used if (cAB <= cA + cB && cBA <= cA + cB) { return K*cAB + L*cBA + (cnt_A - K - L)*cA + (cnt_B - K - L)*cB; } assert(false); } int main(void) { int N, D; scanf("%d %d", &N, &D); for (int i = 0; i < D; ++i) { scanf("%d", &a[i]); --a[i]; } int M; scanf("%d", &M); for (int i = 0; i < M; ++i) { char tip[5]; int a, b; llint x; scanf("%d %d %s %lld", &a, &b, tip, &x); --a, --b; if (tip[0] == 'O') { if (!S[a].count(b) || x < S[a][b]) S[a][b] = x; } if (tip[0] == 'R') { if (!P[a].count(b) || x < P[a][b]) P[a][b] = x; } } // group trips by city pairs map, string> T; for (int i = 0; i + 1 < D; ++i) { int x = a[i]; int y = a[i + 1]; if (x < y) T[{x, y}].push_back('A'); else T[{y, x}].push_back('B'); } llint ans = 0; for (auto& p: T) { int x = p.first.first; int y = p.first.second; string q = p.second; if (!S[x].count(y)) S[x][y] = inf; if (!P[x].count(y)) P[x][y] = inf; if (!S[y].count(x)) S[y][x] = inf; if (!P[y].count(x)) P[y][x] = inf; llint cost = solve(q, S[x][y], S[y][x], P[x][y], P[y][x]); ans += cost; } printf("%lld\n", ans); return 0; }