#include <bits/stdc++.h>
using namespace std;

#define M1 1000000007
#define M3 1000000009
#define M2 998244353
#define ll long long
#define ld long double
#define pll pair<ll,ll>
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define repr(i,a,b) for(ll i=b-1;i>=a;i--)
#define forr(i,n) for(ll i=0;i<n;i++)
#define F first
#define S second
#define pb push_back
#define DB pop_back
#define mp make_pair
#define MT make_tuple
#define V(a) vector<a>
#define vi vector<ll>
#define endl '\n'
#define ce(ele) cout<<ele<<' '
#define cs(ele) cout<<ele<<'\n'
#define csv(v) for(int i=0;i<v.size();i++)cout<<v[i]<<' '
#define yep cout<<"YES"<<'\n'
#define nope cout<<"NO"<<'\n'
#define CASE(te) ll te; cin>>te; while(te--)
#define sor(v) sort(v.begin(),v.end())
#define rev(v) reverse(v.begin(),v.end())

void FAST() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
}
vi arr[2001];
int vis[2001];
void dfs(int node)
{
    vis[node]=1;
    
    for(auto x:arr[node])
    {
        if(vis[x]==0)
        {
            dfs(x);
        }
    }
}

int main()
{
  FAST();
  ll n,m;
  cin>>n>>m;
  forr(i,m)
  {
        ll a,b;
        cin>>a>>b;
        arr[a].push_back(b);
  }
  ll ans=0;
  for(int i=1;i<=n;i++)
  {
        dfs(i);
        ll c=0;
        for(int j=1;j<=n;j++)
        if(vis[j]==1)
        {
              c++;
              vis[j]=0;
        }

        ans+=c;
  }
  cs(ans);

}
#include <bits/stdc++.h>

using namespace std;

typedef long long int ll;
typedef pair<ll, ll> pll;

#define FOR(i, n, m) for(ll (i)=(m);(i)<(n);++(i))
#define REP(i, n) FOR(i,n,0)
#define OF64 std::setprecision(40)

const ll MOD = 1000000007;
const ll INF = (ll) 1e15;

struct Vertex {
    vector<pll> node;
};
Vertex V[2005];

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    ll N, M;
    cin >> N >> M;
    REP(i, M) {
        ll a, b, c;
        cin >> a >> b >> c;
        a--;
        b--;
        V[a].node.push_back(pll(b, c));
    }

    REP(i, N) {
        vector<ll> dist(N, INF);
        priority_queue<pll, vector<pll>, function<bool(pll, pll)>> q([](pll a, pll b) { return a.second > b.second; });
        q.push(pll(i, 0));
        while (!q.empty()) {
            pll t = q.top();
            q.pop();
            if(dist[t.first]<t.second)continue;
            for (auto &v : V[t.first].node) {
                ll nxt = v.first;
                ll cost = t.second + v.second;
                if (dist[nxt] <= cost)
                    continue;
                dist[nxt] = cost;
                q.push(pll(nxt, cost));
            }
        }

        ll ret = dist[i];
        if (ret == INF)
            ret = -1;
        cout << ret << endl;
    }
    return 0;
}