Source Code
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    #ifndef ONLINE_JUDGE
        freopen("in.txt", "r", stdin);
        freopen("out.txt", "w", stdout);
    #endif
    int n, m;
    cin >> n >> m;
    vector<set<pair<int, pair<int, int>>>> g(n);
    vector<array<int, 3>> edges(m);
    for (auto& i : edges) {
        cin >> i[0] >> i[1] >> i[2];
        i[0]--; i[1]--;
    }
    string s;
    cin >> s;
    for (auto& i : edges) {
        g[i[0]].insert(make_pair(s[i[1]] - 'a', make_pair(i[2], i[1])));
        g[i[1]].insert(make_pair(s[i[0]] - 'a', make_pair(i[2], i[0])));
    }
    ll ans = 1e10;
    for (int k = 0; k < n; ++k) {
        for (auto& i : g[k]) {
            if (s[k] - 'a' == i.first) ans = min<ll>(ans, i.second.first);
            auto it = g[i.second.second].lower_bound(make_pair(s[k] - 'a', make_pair(-1, -1)));
            vector<ll> take;
            if (it != g[i.second.second].end() && it->first == s[k] - 'a') take.push_back(it->second.first);
            it = next(it);
            if (it != g[i.second.second].end() && it->first == s[k] - 'a') take.push_back(it->second.first);
            if (take.size() < 2) continue;
            ans = min<ll>(ans, take[take[0] == i.second.first] + i.second.first);
        }
    }
    if (ans == 1e10) ans = -1;
    cout << ans << '\n';
    return 0;
}
Copy
Selen With a C Heartbeat
GNU G++17
206 ms
20.0 MB
Accepted