#include #include using namespace std; using i32 = int; using i64 = long long; using i128 = __int128_t; using f64 = double; using p2 = pair; using p3 = tuple; using mint = atcoder::modint998244353; constexpr i64 inf = 1e18; void _main(); int main() { cin.tie(0); ios::sync_with_stdio(false); cout << fixed << setprecision(18); _main(); } void _main() { i64 n, m; cin >> n >> m; vector> g(n), h(n); for (i64 i = 0; i < m; i++) { i64 u, v, c; cin >> u >> v >> c; u--, v--; g[u].push_back({v, c}); h[v].push_back({u, c}); } string s; cin >> s; vector> dp1(n, {{inf, inf}, {inf + 1, inf + 1}}); { priority_queue, greater> que; auto merge = [&](i64 i, p2 x) -> bool { if (dp1[i][0].first > x.first) { if (dp1[i][0].second != x.second) dp1[i] = {x, dp1[i][0]}; else dp1[i] = {x, dp1[i][1]}; return true; } else if (dp1[i][0].second != x.second && dp1[i][1].first > x.first) { dp1[i] = {dp1[i][0], x}; return true; } return false; }; for (i64 i = 0; i < n; i++) { if (s[i] == 'C') { que.push({0, i, i}); merge(i, {0, i}); } } while (!que.empty()) { auto [d, i, j] = que.top(); que.pop(); if (dp1[i][0] != (p2){d, j} && dp1[i][1] != (p2){d, j}) continue; for (auto [ni, c] : h[i]) { if (merge(ni, {d + c, j})) { que.push({d + c, ni, j}); } } } for (i64 i = 0; i < n; i++) { if (s[i] != 'P') dp1[i] = {{inf, inf}, {inf + 1, inf + 1}}; } } vector dp2(n, inf); { priority_queue, greater> que; auto merge = [&](i64 i, p2 x) -> bool { if (dp1[i][0].first > x.first) { if (dp1[i][0].second != x.second) dp1[i] = {x, dp1[i][0]}; else dp1[i] = {x, dp1[i][1]}; return true; } else if (dp1[i][0].second != x.second && dp1[i][1].first > x.first) { dp1[i] = {dp1[i][0], x}; return true; } return false; }; for (i64 i = 0; i < n; i++) { if (s[i] == 'P') { for (auto [x, j] : dp1[i]) { que.push({x, i, j}); } } } while (!que.empty()) { auto [d, i, j] = que.top(); que.pop(); if (dp1[i][0] != (p2){d, j} && dp1[i][1] != (p2){d, j}) continue; for (auto [ni, c] : h[i]) { if (merge(ni, {d + c, j})) { que.push({d + c, ni, j}); } } } for (i64 i = 0; i < n; i++) { if (s[i] == 'C') { dp2[i] = dp1[i][0].second != i ? dp1[i][0].first : dp1[i][1].first; } else dp2[i] = inf; } } { priority_queue, greater> que; for (i64 i = 0; i < n; i++) { if (s[i] == 'C') { que.push({dp2[i], i}); } } while (!que.empty()) { auto [d, i] = que.top(); que.pop(); if (dp2[i] < d) continue; for (auto [ni, c] : h[i]) { if (dp2[ni] > d + c) { dp2[ni] = d + c; que.push({d + c, ni}); } } } for (i64 i = 0; i < n; i++) { if (s[i] != 'K') dp2[i] = inf; } } { priority_queue, greater> que; for (i64 i = 0; i < n; i++) { if (s[i] == 'K') { que.push({dp2[i], i}); } } while (!que.empty()) { auto [d, i] = que.top(); que.pop(); if (dp2[i] < d) continue; for (auto [ni, c] : h[i]) { if (dp2[ni] > d + c) { dp2[ni] = d + c; que.push({d + c, ni}); } } } } cout << (dp2[0] >= inf ? -1 : dp2[0]) << "\n"; }