Source Code
#include <bits/stdc++.h>
using namespace std;

const int oo = 1000000010;
const int N = 100010;

int n, m;
string str;
pair< pair<int, int>, int > arr[N];
vector<int> adj[N][26];

void solve(){
    cin >> n >> m;
    for(int i = 0; i < m; ++i){
        cin >> arr[i].first.first >> arr[i].first.second >> arr[i].second;
    }
    cin >> str;
    str = ' ' + str;
    int ans = oo;
    for(int i = 0; i < m; ++i){
        int u = arr[i].first.first, v = arr[i].first.second, cost = arr[i].second;
        if(str[u] == str[v]){
            ans = min(ans, cost);
        }
        adj[u][str[v] - 'a'].push_back(cost);
        adj[v][str[u] - 'a'].push_back(cost);
    }
    for(int i = 1; i <= n; ++i){
        for(int j = 0; j < 26; ++j){
            if(adj[i][j].size() >= 2){
                sort(adj[i][j].begin(), adj[i][j].end());
                ans = min(ans, adj[i][j][0] + adj[i][j][1]);
            }
        }
    }
    cout << (ans == oo ? -1 : ans);
}

int main(){
    int t = 1;
    //cin >> t;
    while(t--){
        solve();
    }
    return 0;
}
Copy
Selen With a C ItsAboudTime
GNU G++17
217 ms
69.4 MB
Accepted