#include typedef struct List { struct List *next; int v, id; } list; int is_palindrome(char S[]) { int i, j; for (j = 0; S[j] != 0; j++); for (i = 0, j--; i < j; i++, j--) if (S[i] != S[j]) break; if (i < j) return 0; else return 1; } int solve(int N, int M, list* adj[], list e[], char c[], int ans[]) { int i; list *p; for (i = 2; i <= M; i++) if (c[i] != c[1]) break; if (i > M) return -1; int u, w, x = adj[1]->v, par[2][100001][2], dist[2][100001] = {}, q[100001], head, tail; dist[0][x] = 1; q[0] = x; for (head = 0, tail = 1; head < tail; head++) { u = q[head]; for (p = adj[u]; p != NULL; p = p->next) { w = p->v; if (dist[0][w] == 0) { dist[0][w] = dist[0][u] + 1; par[0][w][0] = u; par[0][w][1] = p->id; q[tail++] = w; } } } dist[1][N] = 1; q[0] = N; for (head = 0, tail = 1; head < tail; head++) { u = q[head]; for (p = adj[u]; p != NULL; p = p->next) { w = p->v; if (dist[1][w] == 0) { dist[1][w] = dist[1][u] + 1; par[1][w][0] = u; par[1][w][1] = p->id; q[tail++] = w; } } } int j, k = 0, y, z; char S[200001]; for (j = 1, i = adj[1]->id; j <= M; j++) if (c[j] != c[i]) break; y = e[(j-1)*2].v; z = e[j*2-1].v; ans[k] = i; S[k++] = c[i]; if (dist[0][y] <= dist[0][z]) { k += dist[0][y] - 1; for (i = k - 1, u = y; u != x; i--, u = par[0][u][0]) { ans[i] = par[0][u][1]; S[i] = c[ans[i]]; } if (dist[1][y] < dist[1][z]) { ans[k] = j; S[k++] = c[j]; ans[k] = j; S[k++] = c[j]; for (u = y; u != N; k++, u = par[1][u][0]) { ans[k] = par[1][u][1]; S[k] = c[ans[i]]; } } else { ans[k] = j; S[k++] = c[j]; for (u = z; u != N; k++, u = par[1][u][0]) { ans[k] = par[1][u][1]; S[k] = c[ans[i]]; } } } else { k += dist[0][z] - 1; for (i = k - 1, u = z; u != x; i--, u = par[0][u][0]) { ans[i] = par[0][u][1]; S[i] = c[ans[i]]; } if (dist[1][y] > dist[1][z]) { ans[k] = j; S[k++] = c[j]; ans[k] = j; S[k++] = c[j]; for (u = z; u != N; k++, u = par[1][u][0]) { ans[k] = par[1][u][1]; S[k] = c[ans[i]]; } } else { ans[k] = j; S[k++] = c[j]; for (u = z; u != N; k++, u = par[1][u][0]) { ans[k] = par[1][u][1]; S[k] = c[ans[i]]; } } } if (is_palindrome(S) == 0) return k; else { ans[k] = ans[k-1]; ans[k+1] = ans[k]; return k + 2; } } int main() { int i, N, M, u, w; char c[200001]; list *adj[100001] = {}, e[400001]; scanf("%d %d", &N, &M); for (i = 0; i < M; i++) { scanf("%d %d %c ", &u, &w, &(c[i+1])); e[i*2].v = w; e[i*2+1].v = u; e[i*2].id = i + 1; e[i*2+1].id = i + 1; e[i*2].next = adj[u]; e[i*2+1].next = adj[w]; adj[u] = &(e[i*2]); adj[w] = &(e[i*2+1]); } int ans[200001], k = solve(N, M, adj, e, c, ans); printf("%d\n", k); if (k >= 0) for (i = 0; i < k; i++) printf("%d\n", ans[i]); fflush(stdout); return 0; }