#include <iostream>
#include <vector>

using namespace std;



bool dfs(int u,int v,vector<bool>& led,const vector<vector <int>>& c)
{
    if(u==v) return true;

    if(led[u]) return false;
    led[u]=true;
    for(int i : c[u])
     if(dfs(i,v,led,c))
        return true;
    return false;


}


bool pov(int u, int v, int n, const vector<vector <int>>& c )
{
    vector<bool> led(n, false);
    return dfs(u,v,led,c);

}
# define MAXMN 20000
int main()
{
   int n,m,a,b,d[MAXMN];
   short t;

   cin >> n >> m;
   vector <vector<int>> c(n);
   for(int i=0;i<m;i++)
   {
       cin >> a >> b >> t;
       a--; b--;
       c[a].push_back(b);
       d[a]=t;
   }
   int u,v,brojac=0;
   cin >> u >> v;
   u--; v--;
   if(pov(u,v, n, c))
    {
        for(int i=u;i<v;i++)
         {if(d[i]==1)
            brojac++;
         }
    if(u!=v)
    cout<<brojac+1;
    else
    cout<<0;
    }
    else
    cout << -1;

    return 0;
}