#include<bits/stdc++.h>
#define ll long long
#define fr(i,j,k) for(int i=j;i<k;i++)
#define f(n) fr(i,0,n)
#define f1(n) fr(i,1,n+1)
#define pb push_back
#define F first
#define S second
#define all(x) x.begin(), x.end()
const int mod = 1e9+7;
using namespace std;
int d[1005][1005];
vector<int>g[1005][26];
void solve() {
    int n, m;
    cin >> n >> m;
    vector<pair<int,int>>e;
    f(m) {
        int a, b;
        char c;
        cin >> a >> b >> c;
        e.pb({a, b});
        g[a][c-'a'].pb(b);
        g[b][c-'a'].pb(a);
    }
    queue<pair<int,int>>q;
    q.push({1, n});
    
    memset(d, -1, sizeof(d));
    d[1][n] = 0;
    while (q.size()) {
        auto now = q.front();
        q.pop();
        for (int i = 0 ; i < 26 ; i++) {
            for (auto &j : g[now.F][i]) {
                for (auto &k : g[now.S][i]) {
                    if (d[j][k] == -1) {
                        d[j][k] = d[now.F][now.S] + 2;
                        q.push({j,k});
                    }
                }
            }
        }
    }
    int mn = 1e9;
    f1(n) {
        if (~d[i][i])
            mn = min(mn, d[i][i]);
    }
    for (auto &i : e) {
        if (~d[i.F][i.S]) mn = min(mn, d[i.F][i.S] + 1);
        if (~d[i.S][i.F]) mn = min(mn, d[i.S][i.F] + 1);
    }
    if (mn >1e6) {
        mn = -1;
    }
    cout << mn << '\n';
}
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int t = 1;
    //cin >> t;
    while (t--) {
        solve();
    }
}
#include <iostream>
#include <algorithm>
#include <numeric>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <iomanip>
#include <functional>
#include <bitset>
#include <limits>
#include <cstdio>
#include <cmath>
#include <cassert>
#include <random>

#ifdef DEBUG
#include "library/Utility/debug.cpp"
#else
#define debug(...)
#endif

#define rep(i,n) for(int i=0;i<(n);++i)
#define EL '\n'
#define print(i) std::cout << (i) << '\n'
#define all(v) (v).begin(), (v).end()
using lnt = long long;
struct FIO{FIO(){std::cin.tie(0);std::ios_base::sync_with_stdio(0);std::cout<<std::fixed<<std::setprecision(15);}}fIO;
template<typename T> using V = std::vector<T>;
template<typename T> void fill(V<T>&v) { for(T&e:v) std::cin >> e; }
/*-*/

int main() {
	lnt n,t;
	std::cin >> n >> t;
	V<lnt> a(n);
	fill(a);
	V<lnt> x;
	x.reserve((int)2e6);
	lnt m=n/2;
	x.emplace_back(0);
	rep(s,1<<m) {
		lnt sum=0;
		rep(i,m) {
			if(s>>i&1) sum+=a[i];
		}
		if(sum<=t) x.emplace_back(-sum);
	}
	std::set<lnt> set1(all(x));
	lnt max=-*set1.lower_bound(-t);
	rep(s,1<<(n-m)) {
		lnt sum=0;
		rep(i,(n-m)) {
			if(s>>i&1) sum+=a[m+i];
		}
		if(sum<=t) {
			auto lb=set1.lower_bound(-t+sum);
			max=std::max(max,sum-*lb);
		}
	}
	print(max);
}
