#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 5;
vector<pair<int, int>> g[N];
int visited[N];
int in[N];
int out[N];
pair<int, int> p;
struct trip {
  int x;
  int y;
  int z;
};
vector<trip> ans;
void dfs(int src) {
  for (auto x : g[src]) {
    dfs(x.first);
    p.second = min(p.second, x.second);
  }
  if (out[src] == 0) {
    p.first = src;
  }
}
int main() {
  ios_base::sync_with_stdio(), cout.tie(NULL), cin.tie(NULL);
  ;
  memset(visited, false, sizeof(visited));
  memset(in, 0, sizeof(in));
  memset(out, 0, sizeof(out));
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int x, y, z;
    cin >> x >> y >> z;
    g[x].push_back({y, z});
    in[y]++;
    out[x]++;
  }
  for (int i = 1; i <= n; i++) {
    if (in[i] == 0 && out[i]) {
      p.first = i;
      p.second = INT_MAX;
      dfs(i);
      ans.push_back({i, p.first, p.second});
    }
  }
  cout << ans.size() << endl;
  for (int i = 0; i < ans.size(); i++) {
    cout << ans[i].x << " " << ans[i].y << " " << ans[i].z << endl;
  }
  return 0;
}
