// yukicoder: No.340 雪の足跡 // 2019.7.28 bal4u #include #include typedef long long ll; #if 1 #define gc() getchar_unlocked() #else #define gc() getchar() #endif int in() { // 非負整数の入力 int n = 0, c = gc(); do n = 10 * n + (c & 0xf); while ((c = gc()) >= '0'); return n; } #define HASHSIZ 50000017 long long hash[HASHSIZ+5], *hashend = hash+HASHSIZ; int insert(int b1, int b2) { long long t, *p; if (b1 > b2) t = b1, b1 = b2, b2 = t; t = ((long long)b2 << 20) | b1; p = hash + (int)(t % HASHSIZ); while (*p) { if (*p == t) return 1; if (++p == hashend) p = hash; } *p = t; return 0; } //// 優先度付きキュー(ダイクストラ法用) #define MAX 100000 typedef struct { int t, n; } QUE; QUE que[MAX]; int qsize; #define PARENT(i) ((i)>>1) #define LEFT(i) ((i)<<1) #define RIGHT(i) (((i)<<1)+1) void min_heapify(int i) { int l, r, min; QUE qt; l = LEFT(i), r = RIGHT(i); if (l < qsize && que[l].t < que[i].t) min = l; else min = i; if (r < qsize && que[r].t < que[min].t) min = r; if (min != i) { qt = que[i]; que[i] = que[min]; que[min] = qt; min_heapify(min); } } void deq() { que[0] = que[--qsize]; min_heapify(0); } int qmax; void enq(int n, int t) { int i, min; QUE qt; i = qsize++; que[i].t = t, que[i].n = n; while (i > 0 && que[min = PARENT(i)].t > que[i].t) { qt = que[i]; que[i] = que[min]; que[min] = qt; i = min; } } //// 本問題関連 #define MAXV 9999991 int W, H; int to[MAXV][4]; char vis[MAXV]; int dijkstra(int start, int goal) { int i, n, t, nx; enq(start, 0); while (qsize) { n = que[0].n, t = que[0].t, deq(); //printf("n=%d, t=%d, qsize=%d, start=%d, goal=%d\n", n, t, qsize, start, goal); if (n == goal) return t; if (vis[n]) continue; vis[n] = 1; for (i = 0; i < 4; i++) if ((nx = to[n][i]) >= 0) { if (!vis[nx]) enq(nx, t+1); } } return -1; } void setup(int b1, int b2) { if (insert(b1, b2)) return; if (b1 < b2) { if (b2-b1 < W) { while (b1 < b2) to[b1][1] = b1+1, to[b1+1][3] = b1, b1++; } else { while (b1 < b2) to[b1][0] = b1+W, to[b1+W][2] = b1, b1+=W; } } else { if (b1-b2 < W) { while (b2 < b1) to[b2][1] = b2+1, to[b2+1][3] = b2, b2++; } else { while (b2 < b1) to[b2][0] = b2+W, to[b2+W][2] = b2, b2+=W; } } } int main() { int k, N, M, b1, b2; W = in(), H = in(), N = in(); if (N == 0) { puts(W*H == 1? "0": "Odekakedekinai.."); return 0; } memset(to, -1, sizeof(to)); while (N--) { M = in(), b1 = in(); while (M--) { b2 = in(), setup(b1, b2), b1 = b2; } } if ((k = dijkstra(0, W*H-1)) < 0) puts("Odekakedekinai.."); else printf("%d\n", k); return 0; }