#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#define N 2005
#define mp make_pair
using namespace std;
int read()
{
	int x=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+(ch^48);ch=getchar();}
	return x*f;
}	
int n,m,f[N][N],dist[N],vis[N],v[N],w[N],head[N],nxt[N],cnt,self_circle[N];
void add(int a,int b,int c)
{
	v[++cnt]=b;
	w[cnt]=c;
	nxt[cnt]=head[a];
	head[a]=cnt;
}
void dij(int S)
{
	memset(dist,0x3f,sizeof(dist));
	memset(vis,0,sizeof(vis));
	priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > >q;
	q.push(mp(0,S));
	dist[S]=0;
	while(!q.empty())
	{
		int c=q.top().second;q.pop();
		if(vis[c])continue;
		vis[c]=1;
		for(int i=head[c];i;i=nxt[i])
		{
			if(dist[v[i]]>dist[c]+w[i])
			{
				dist[v[i]]=dist[c]+w[i];
				q.push(mp(dist[v[i]],v[i]));
			}
		}
	}
}
int main()
{
	memset(self_circle,0x3f,sizeof(self_circle));
	n=read();m=read();
	for(int i=1;i<=m;i++)
	{
		int x=read(),y=read(),z=read();
		if(x==y)self_circle[x]=min(self_circle[x],z);
		else add(x,y,z);
	}
	for(int i=1;i<=n;i++)
	{
		dij(i);
		memcpy(f[i],dist,sizeof(f[i]));
	}
//	for(int i=1;i<=n;i++)
//	{
//		for(int j=1;j<=n;j++)
//		{
//			printf("%d ",f[i][j]);
//		}
//		puts("");
//	}
	for(int i=1;i<=n;i++)
	{
		int minn=self_circle[i];
		for(int j=1;j<=n;j++)
		{
			if(i==j)continue;
			minn=min(minn,f[i][j]+f[j][i]);
		}
		if(minn==0x3f3f3f3f)puts("-1");
		else printf("%d\n",minn);
	}
	return 0;
}

#include <bits/stdc++.h>
#define ll int 
#define MAXN 2005
#define MAX 2005
using namespace std;

vector<ll> adjlist[MAX];
ll n, m;

ll bfs(ll start) {
    ll mark[MAX], res = 0;
    memset(mark, 0, sizeof(mark));
    queue<ll> q;
    q.push(start);
    mark[start] = 1;
    while(!q.empty()) {
        ll top = q.front();
        q.pop();
        for(ll i = 0; i < adjlist[top].size(); i++) {
            ll next_cur = adjlist[top][i];
            if(!mark[next_cur]) {
                q.push(next_cur);
                mark[next_cur] = 1;
            }
        }
    }
    
    for(ll i = 1; i <= n; i++) {
        if(mark[i])
            res++;
    }
        
    return res;
}

int main() {
    
    cin>>n>>m;
    for(ll i = 0 ; i < m; i++) {
        ll u,v;
        cin>>u>>v;
        adjlist[u].push_back(v);
    }
    ll ans = 0;
    for(ll i = 1; i <= n; i++) {
        ans += bfs(i);
    }
    cout<<ans<<endl;
	return 0;
}
