#include <bits/stdc++.h>
using namespace std;
list<pair<long long int, long long int> > l[1010];
long long int in[1010], out[1010], visited[1010], used[1010];
typedef struct node {
  long long int x, y, d;
} node;
bool my(node a, node b) {
  if (a.x < b.x)
    return true;
  else if (a.x == b.x) {
    if (a.y < b.y) return true;
  }
  return false;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long int n, p;
  cin >> n >> p;
  long long int i, x, y, d, mc;
  memset(in, 0, sizeof(in));
  memset(out, 0, sizeof(out));
  memset(used, 0, sizeof(used));
  memset(visited, 0, sizeof(visited));
  for (i = 0; i < p; i++) {
    cin >> x >> y >> d;
    x--;
    y--;
    l[x].push_back(make_pair(y, d));
    in[y]++;
    out[x]++;
    used[x] = 1;
    used[y] = 1;
  }
  vector<node> res;
  node t;
  if (p) {
    for (i = 0; i < n; i++) {
      if (in[i] == 0 && used[i]) {
        pair<long long int, long long int> p2, p3;
        stack<pair<long long int, long long int> > s;
        s.push(make_pair(i, INT_MAX));
        t.x = i;
        mc = INT_MAX;
        while (!s.empty()) {
          p2 = s.top();
          s.pop();
          if (!visited[p2.first]) {
            mc = min(mc, p2.second);
            if (out[p2.first] == 0) {
              t.y = p2.first;
            }
            visited[p2.first] = 1;
            list<pair<long long int, long long int> >::iterator it;
            for (it = l[p2.first].begin(); it != l[p2.first].end(); it++) {
              p3 = *it;
              if (!visited[p3.first]) {
                s.push(p3);
              }
            }
          }
        }
        t.d = mc;
        t.x++;
        t.y++;
        res.push_back(t);
      }
    }
  }
  sort(res.begin(), res.end(), my);
  cout << res.size() << endl;
  for (i = 0; i < res.size(); i++) {
    cout << res[i].x << " " << res[i].y << " " << res[i].d << endl;
  }
  return 0;
}
