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<vector<array<int, 2>>> g(n);
    vector<array<int, 3>> edges;
    for (int i = 0, a, b, c; i < m; ++i) {
        cin >> a >> b >> c; --a; --b;
        g[a].push_back({b, c});
        g[b].push_back({a, c});
        edges.push_back({a, b, c});
    }
    string s;
    cin >> s;
    ll ans = 1e10;
    for (auto &i : edges) {
        if (s[i[0]] == s[i[1]]) ans = min<ll>(ans, i[2]);
        for (int j = 0; j < 2; ++j) {
            for (auto &k : g[i[j]]) {
                if (s[i[j]] == s[k[0]]) ans = min<ll>(ans, i[2] + k[1]);
            }
        }
    }
    if (ans == 1e10) ans = -1;
    cout << ans << '\n';
    return 0;
}
Copy
Selen With a C Heartbeat
GNU G++17
2072 ms
9.7 MB
Time Limit Exceeded