#include using namespace std; #define rep(i, x) for(int i = 0; i < (x); i++) constexpr int inf = 1 << 30; using T = tuple; int n, m, bit, s, x, y, xy_id; char sc; string str; int main() { cin >> n >> m; vector edges; vector>> g(n); auto is_palindrome = [](const string &s) { rep(i, s.size()) { if(s[i] != s[s.size() - 1 - i]) return false; } return true; }; auto bfs = [&](const int s) { vector dist(n, inf); dist[s] = 0; queue que; que.push(s); while(que.size()) { int now = que.front(); que.pop(); for(auto [to, ignored] : g[now]) { if(dist[to] <= dist[now] + 1) continue; dist[to] = dist[now] + 1; que.push(to); } } return dist; }; auto restore = [&](vector &vec, const int s, const int t) { vector res; auto dist = bfs(s); int now = t; while(now != s) { for(auto [to, id] : g[now]) { if(dist[to] + 1 == dist[now]) { now = to; res.push_back(id); break; } } } reverse(res.begin(), res.end()); vec.insert(vec.end(), res.begin(), res.end()); }; rep(i, m) { int a, b; char c; cin >> a >> b >> c; --a, --b; g[a].emplace_back(b, i); g[b].emplace_back(a, i); edges.push_back({a, b, c - 'a'}); bit |= 1 << (c - 'a'); } if(__builtin_popcount(bit) == 1) { puts("-1"); return 0; } //方針 //0-s s-x x-y y-x x-(n-1) の順にパスを求める vector res; rep(i, m) { auto [u, v, ig] = edges[i]; if(!u or !v) { s = max(u, v); res.push_back(i); sc = get<2>(edges[i]); break; } } rep(i, m) { auto [u, v, c] = edges[i]; if(c != sc) { auto dist = bfs(s); if(dist[u] > dist[v]) swap(u, v); x = u, y = v, xy_id = i; break; } } restore(res, s, x); rep(i, 2) res.push_back(xy_id); restore(res, x, n - 1); for(auto v : res) str.push_back(get<2>(edges[v])); if(is_palindrome(str)) rep(i, 2) res.push_back(res.back()); cout << res.size() << endl; for(auto &v : res) cout << v + 1 << endl; return 0; }