#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct node
{
int next, time;
};
int degree[2][110], t[2][110], maxtime;
vector<node> v[2][110];
int torder(int index, int n)
{
int i;
queue<int> q;
for(i = 1; i <= n; i++)
{
if(degree[index][i] == 0)
{
if(index == 1)
{
t[1][i] = maxtime;
}
q.push(i);
}
}
int cur, size, next, nexttime[2], curtime, count = 0;
while(q.size() > 0)
{
cur = q.front();
q.pop();
count++;
size = v[index][cur].size();
for(i = 0; i < size; i++)
{
next = v[index][cur][i].next;
degree[index][next]--;
if(degree[index][next] == 0)
{
q.push(next);
}
curtime = t[index][cur];
nexttime[0] = curtime + v[index][cur][i].time;
nexttime[1] = curtime - v[index][cur][i].time;
if(index == 0 && nexttime[0] > t[0][next])
{
t[0][next] = nexttime[0];
}
else if(index == 1 && nexttime[1] < t[1][next])
{
t[1][next] = nexttime[1];
}
}
if(index == 0 && t[0][cur] > maxtime)
{
maxtime = t[0][cur];
}
}
if(count < n)
{
return 0;
}
return 1;
}
int main()
{
int n, m;
scanf("%d%d", &n, &m);
int i, a, b;
node nod;
for(i = 1; i <= m; i++)
{
scanf("%d%d%d", &a, &b, &nod.time);
nod.next = b;
v[0][a].push_back(nod);
nod.next = a;
v[1][b].push_back(nod);
degree[1][a]++;
degree[0][b]++;
}
for(i = 1; i <= n; i++)
{
t[0][i] = 0;
t[1][i] = 100000000;
}
for(i = 0; i <= 1; i++)
{
if(torder(i, n) == 0)
{
printf("0\n");
return 0;
}
}
printf("%d\n", maxtime);
int size, j, next;
for(i = 1; i <= n; i++)
{
size = v[0][i].size();
for(j = size - 1; j >= 0; j--)
{
next = v[0][i][j].next;
if(t[1][next] - t[0][i] == v[0][i][j].time)
{
printf("%d->%d\n", i, next);
}
}
}
system("pause");
return 0;
}