#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
#define NMAX 250012
#define INFI 0x3f3f3f3f
int n, m, x, y;
#define DIM 4000000
char buf[DIM];
int poz;
#define cin(x) \
{ \
x = 0; \
while(buf[poz] < '0' || buf[poz] > '9') \
if(++poz == DIM) \
fread(buf, 1, DIM, stdin), poz = 0; \
while(buf[poz] >= '0' && buf[poz] <= '9') \
{ \
x = x*10 + (buf[poz]-'0'); \
if(++poz == DIM) \
fread(buf, 1, DIM, stdin), poz = 0; \
} \
}
#define MAX(a, b) ((a) > (b)) ? (a) : (b)
#define MIN(a, b) ((a) < (b)) ? (a) : (b)
vector<int> a[NMAX], p[NMAX], k[1002];
int _max = -INFI, _min[NMAX];
void read()
{
//fread(buf, 1, DIM, stdin);
//cin(n); cin(m); cin(x); cin(y);
scanf("%d%d%d%d", &n, &m, &x, &y);
for(int i = 1, q, w, e; i <= m; ++i)
{
// cin(q); cin(w); cin(e);
scanf("%d%d%d", &q, &w, &e);
a[q].push_back(w);
p[q].push_back(e);
_max = MAX(_max, e);
}
}
int main()
{
freopen("pscnv.in", "r", stdin);
freopen("pscnv.out", "w", stdout);
read();
memset(_min, INFI, sizeof(_min));
_min[x] = 0;
int i;
vector<int> :: iterator nod, cost, fin1, fin2, it;
k[0].push_back(x);
for(i = 0; i <= _max; ++i)
{
for(it = k[i].begin(), fin1 = k[i].end(); it != fin1; ++it)
{
if(_min[*it] < i)
continue;
for(nod = a[*it].begin(), cost = p[*it].begin(), fin2 = a[*it].end(); nod != fin2; ++nod, ++cost)
{
_min[*nod] = MIN(_min[*nod], MAX(*cost, _min[*it]));
k[ _min[*nod] ].push_back(*nod);
}
}
}
printf("%d\n", _min[y]);
return 0;
}