// yukicoder: 17 2つの地点に泊まりたい // 2019.5.27 bal4u #include #include //// 高速入力 #if 1 #define gc() getchar_unlocked() #else #define gc() getchar() #endif int in() // 非負整数の入力 { int n = 0, c = gc(); // while (isspace(c)) c = gc(); do n = 10 * n + (c & 0xf), c = gc(); while (c >= '0'); return n; } //// 優先度付きキュー(ダイクストラ法用) #define MAX 1000000 typedef struct { int t, n, a, b; } 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 a, int b) { int i, min; QUE qt; i = qsize++; que[i].t = t, que[i].n = n, que[i].a = a, que[i].b = b; 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 52 int N; int hi[MAXV], to[MAXV][MAXV], tm[MAXV][MAXV]; char vis[MAXV][MAXV][MAXV]; int S[MAXV]; int dijkstra(int start, int goal) { int i, n, t, a, b, nx, nt; enq(start, 0, 0, 0); while (qsize) { n = que[0].n, t = que[0].t, a = que[0].a, b = que[0].b, deq(); if (n == goal && a > 0 && b > 0) return t; if (vis[n][a][b]) continue; vis[n][a][b] = 1; for (i = 0; i < hi[n]; i++) { nx = to[n][i], nt = t + tm[n][i]; if (!vis[nx][a][b]) enq(nx, nt, a, b); if (n > start && n < goal) { if (a == 0 && !vis[nx][n][b]) enq(nx, nt + S[n], n, b); else if (b == 0 && n != a && !vis[nx][a][n]) enq(nx, nt + S[n], a, n); } } } return -1; } int main() { int i, k, M, a, b, c; N = in(); for (i = 0; i < N; i++) S[i] = in(); M = in(); while (M--) { a = in(), b = in(), c = in(); k = hi[a]++, to[a][k] = b, tm[a][k] = c; k = hi[b]++, to[b][k] = a, tm[b][k] = c; } printf("%d\n", dijkstra(0, N-1)); return 0; }