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

	int main(){

	    int t = 1;
	    //cin >> t;

	    while(t--){
	    	int n, m;
	    	cin >> n >> m;

	    	vector<pair<int,int>>a[n + 1];

	    	for(int i = 0 ; i < m ; i++){
	    		int u, v, w;
	    		scanf("%d%d%d",&u,&v,&w);
	    		u--; v--;
	    		a[u].pb({v,w});
	    		a[v].pb({u,w});
	    	}
	    	string s;
	    	cin >> s;

	    	long long ans = 10000000100;
	    	vector<int>v[n + 1][26];

	    	for(int i = 0 ; i < n ; i++){
	    		for(int j = 0 ; j < a[i].size() ; j++){
	    			v[i][s[a[i][j].first]- 'a'].pb(a[i][j].second);
	    			if(s[a[i][j].first] == s[i])ans = min((int)ans, a[i][j].second);
	    		}
	    	}

	    	for(int i = 0 ; i < n ; i++){
	    		for(int j = 0 ; j < 26 ; j++){
	    			sort(v[i][j].begin(), v[i][j].end());
	    			if(v[i][j].size() > 1)
	    			ans = min(ans, (long long)v[i][j][0] + v[i][j][1]);
	    		}
	    	}
	    	cout<<(ans == 10000000100 ? -1 : ans);
	    }
	}
 


Copy
Selen With a C Abdullahbitar
GNU G++17
121 ms
73.5 MB
Accepted