// yukicoder: No.614 壊れたキャンパス // 2019.5.7 bal4u #include #include #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 { long long t; int b, f; } 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 b, int f, long long t) { int i, min; QUE qt; i = qsize++; que[i].t = t, que[i].b = b, que[i].f = f; while (i > 0 && que[min = PARENT(i)].t > que[i].t) { qt = que[i]; que[i] = que[min]; que[min] = qt; i = min; } } //// ハッシュテーブル #define HASHSIZ 500009 typedef struct { int b, f; } HASH; HASH hash[HASHSIZ+5], *hashend = hash + HASHSIZ; int lookup(int b, int f) { HASH *p = hash + (int)((((long long)b << 32) + f) % HASHSIZ); while (p->f) { if (p->b == b && p->f == f) return 1; if (++p == hashend) p = hash; } return 0; } int insert(int b, int f) { HASH *p = hash + (int)((((long long)b << 32) + f) % HASHSIZ); while (p->f) { if (p->b == b && p->f == f) return 1; if (++p == hashend) p = hash; } p->b = b, p->f = f; return 0; } //// 本問題関連 #define MAXB 200005 typedef struct { int me; int b, f; } T; // floor(me), b,f(your bluding/floor) T *to[MAXB]; int hi[MAXB]; int N; #define ABS(x) ((x)>=0?(x):-(x)) long long dijkstra(int sb, int sf, int tb, int tf) { int i, b, f, nb, nf; long long t, nt; enq(sb, sf, 0); while (qsize) { b = que[0].b, f = que[0].f, t = que[0].t, deq(); if (b == tb && f == tf) return t; if (insert(b, f)) continue; for (i = 0; i < hi[b]; i++) { nb = to[b][i].b, nf = to[b][i].f; if (lookup(nb, nf)) continue; nt = t + ABS(to[b][i].me - f); enq(nb, nf, nt); } } return -1LL; } int main() { int i, k, a, b, c, M, K, S, T; int *memo, sz; N = in(), M = in(), K = in(), S = in(), T = in(); memo = malloc(sizeof(int)*M*3); sz = 0; for (i = 0; i < M; i++) { memo[sz++] = a = in()-1, memo[sz++] = in(), memo[sz++] = in(); hi[a]++, hi[a+1]++; } if (hi[N-1]++ == 0) { puts("-1"); return 0; } for (i = 0; i < N; i++) if (hi[i]) to[i] = malloc(sizeof(T)*hi[i]); memset(hi, 0, sizeof(int)*N); i = 0; while (i < sz) { a = memo[i++], b = memo[i++], c = memo[i++]; k = hi[a]++, to[a ][k].me = b, to[a ][k].b = a+1, to[a ][k].f = c; k = hi[a+1]++, to[a+1][k].me = c, to[a+1][k].b = a, to[a+1][k].f = b; } k = hi[N-1]++, to[N-1][k].me = to[N-1][k].f = T, to[N-1][k].b = N-1; printf("%lld\n", dijkstra(0, S, N-1, T)); return 0; }