#include <bits/stdc++.h>
using namespace std;
struct hash_pair {
  template <class T1, class T2>
  size_t operator()(const pair<T1, T2> &p) const {
    auto hash1 = hash<T1>{}(p.first);
    auto hash2 = hash<T2>{}(p.second);
    return hash1 ^ hash2;
  }
};
long long int n, m;
vector<pair<long long int, long long int>> adj[1001];
bool visited[1001];
long long int start[1];
long long int end[1];
long long int parent[1];
long long int level[1];
vector<long long int> dfs_order;
long long int d = numeric_limits<long long int>::max();
long long int cycle = 0;
void dfs(long long int node) {
  if (cycle == 0) {
  } else {
    visited[node] = true;
  }
  for (auto next : adj[node]) {
    if (!visited[next.first]) {
      cycle = next.first;
      if (next.second < d) {
        d = next.second;
      }
      dfs(next.first);
    }
  }
}
long long int lift(long long int a, long long int dist,
                   vector<vector<long long int>> &up) {
  for (long long int i = 0; i < 20; i++) {
    if (dist & (1 << i)) {
      a = up[a][i];
    }
  }
  return a;
}
void preprocesslift(vector<vector<long long int>> &up) {
  for (long long int j = 1; j < 20; j++) {
    for (long long int i = 1; i <= n; i++) {
      if (up[i][j - 1] != -1) {
        up[i][j] = up[up[i][j - 1]][j - 1];
      }
    }
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long int t = 1;
  while (t > 0) {
    cin >> n;
    long long int p;
    cin >> p;
    vector<tuple<int, int, int>> ans;
    vector<pair<int, long long int>> checker[1001];
    for (long long int i = 0; i < p; i++) {
      long long int x, y, z;
      cin >> x >> y >> z;
      adj[x].push_back(make_pair(y, z));
      checker[y].push_back(make_pair(x, z));
    }
    for (long long int i = 1; i <= n; i++) {
      if (!visited[i] && checker[i].size() == 0) {
        dfs(i);
      }
      if (cycle != 0 && cycle != i) {
        ans.push_back(make_tuple(i, cycle, d));
      }
      d = numeric_limits<long long int>::max();
      cycle = 0;
    }
    cout << ans.size() << "\n";
    for (int i = 0; i < ans.size(); i++) {
      cout << get<0>(ans[i]) << " " << get<1>(ans[i]) << " " << get<2>(ans[i])
           << " ";
      cout << "\n";
    }
    t--;
  }
  return 0;
}
