#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000;
const int INF = 1e7;
bool is[maxn];
bool flag[maxn];
int n, p;
vector<int> v[maxn][2];
vector<int> g[maxn][2];
void dfs(int a) {
  if (v[a][0].size() == 0) {
    g[a][0].push_back(a);
    g[a][1].push_back(INF);
  }
  is[a] = true;
  for (int i = 0; i < (int)v[a][0].size(); ++i) {
    int V = v[a][0][i];
    if (!is[V]) {
      dfs(V);
    }
    if (g[V][0].size() != 0) {
      for (int j = 0; j < (int)g[V][0].size(); ++j) {
        g[a][0].push_back(g[V][0][i]);
        int t = min(g[V][1][i], v[a][1][i]);
        g[a][1].push_back(t);
      }
      g[V][0].clear();
    }
  }
}
int main() {
  cin >> n >> p;
  for (int i = 0; i < p; ++i) {
    int a, b, c;
    cin >> a >> b >> c;
    --a, --b;
    v[a][0].push_back(b);
    v[a][1].push_back(c);
  }
  for (int i = 0; i < n; ++i) {
    if (!is[i]) {
      dfs(i);
    }
  }
  int ans = 0;
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < (int)g[i][0].size(); ++j)
      if (g[i][1][j] < INF) ++ans;
  cout << ans << endl;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < (int)g[i][0].size(); ++j) {
      if (g[i][1][j] < INF)
        cout << i + 1 << " " << g[i][0][j] + 1 << " " << g[i][1][j] << endl;
    }
  }
  return 0;
}
