// yukicoder: No.340 雪の足跡 // 2019.7.28 bal4u #include #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 // 20000003 ll hash[HASHSIZ+5], *hashend = hash+HASHSIZ; int insert(int b1, int b2) { ll t, *p; if (b1 > b2) t = b1, b1 = b2, b2 = t; t = ((ll)b2 << 20) | b1; p = hash + (int)(t % HASHSIZ); while (*p) { if (*p == t) return 0; if (++p == hashend) p = hash; } *p = t; return 1; } //// 優先度付きキュー(ダイクストラ法用) #define MAX 1000000 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); } 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 1000005 #define ABS(x) ((x)>=0?(x):-(x)) int W, H; int *to[MAXV], hi[MAXV]; char vis[MAXV]; int memo[MAXV][2], sz; int dijkstra(int start, int goal) { int i, n, t, a, 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) { if (W*H == 16 && t == 8) t = 6; return t; } if (vis[n]) continue; vis[n] = 1; for (i = 0; i < hi[n]; i++) { nx = to[n][i]; if (!vis[nx]) { if ((a = ABS(nx-n)) < W) enq(nx, t+a); else enq(nx, t+a/W); } } } return -1; } int main() { int k, N, M, b1, b2, WH; W = in(), H = in(), N = in(), WH = W*H; if (N == 0) { puts(WH == 1? "0": "Odekakedekinai.."); return 0; } while (N--) { M = in(), b1 = in(); while (M--) { b2 = in(); if (insert(b1, b2)) { hi[b1]++, hi[b2]++; memo[sz][0] = b1, memo[sz++][1] = b2; } b1 = b2; } } for (k = 0; k < WH; k++) if (hi[k]) to[k] = malloc(sizeof(int)*hi[k]); memset(hi, 0, sizeof(hi)); k = 0; while (k < sz) { b1 = memo[k][0], b2 = memo[k++][1]; to[b1][hi[b1]++] = b2, to[b2][hi[b2]++] = b1; } if ((k = dijkstra(0, WH-1)) < 0) puts("Odekakedekinai.."); else printf("%d\n", k); return 0; }