Source Code
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 1e5 + 1;
vector<int> g[N][26];
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<array<int, 3>> edges(m);
    for (auto& i : edges) {
        cin >> i[0] >> i[1] >> i[2];
        i[0]--; i[1]--;
    }
    string s;
    cin >> s;
    ll ans = 1e10;
    for (auto &i : edges) {
        if (s[i[0]] == s[i[1]]) ans = min<ll>(ans, i[2]);
        g[i[0]][s[i[1]] - 'a'].push_back(i[2]);
        g[i[1]][s[i[0]] - 'a'].push_back(i[2]);
    }
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < 26; ++j) {
            if (g[i][j].size() < 2) continue;
            sort(g[i][j].begin(), g[i][j].end());
            ans = min<ll>(ans, g[i][j][0] + g[i][j][1]);
        }
    }
    if (ans == 1e10) ans = -1;
    cout << ans << '\n';
    return 0;
}
Copy
Selen With a C Heartbeat
GNU G++17
96 ms
69.3 MB
Accepted