#include <bits/stdc++.h>
using namespace std;
const int N = 1100;
int n, m, deg[2][N], dp[N][N];
vector<pair<int, int>> adj[N];
bool mark[N];
vector<int> match[2];
void read() {
  cin >> n >> m;
  int v, u, d;
  for (int i = 0; i < m; i++) {
    cin >> v >> u >> d;
    adj[v].push_back({u, d});
    deg[0][v]++, deg[1][u]++;
    dp[v][u] = max(dp[v][u], d);
    dp[u][v] = max(dp[u][v], d);
  }
}
void dfs(int v, int ind) {
  mark[v] = true;
  bool cld = false;
  for (auto u : adj[v])
    if (!mark[u.first]) dfs(u.first, ind), cld = true;
  if (!cld)
    cout << match[0][ind] << ' ' << v << ' ' << dp[match[0][ind]][v] << endl;
}
int main() {
  ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  read();
  for (int i = 1; i <= n; i++)
    if (deg[0][i] + deg[1][i] == 1 && deg[0][i] == 1)
      match[0].push_back(i);
    else if (deg[0][i] + deg[1][i] == 1 && deg[1][i] == 1)
      match[1].push_back(i);
  for (int k = 1; k <= n; k++)
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= n; j++)
        dp[i][j] = max(dp[i][j], min(dp[i][k], dp[k][j]));
  cout << match[0].size() << endl;
  for (int i = 0; i < match[0].size(); i++) dfs(match[0][i], i);
  return 0;
}
