#include <bits/stdc++.h>
using namespace std;
void err(istream_iterator<string> it) { cerr << endl; }
template <typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
  cerr << *it << " = " << a << endl;
  err(++it, args...);
}
const int N = 1000 + 5, mod = 1000000007;
int n, edges;
vector<pair<int, int>> graph[N];
bool cycle;
bool vis[N];
int mxmDepth, indx, mnmDiameter;
void dfs(int node, int dep) {
  vis[node] = true;
  if (mxmDepth < dep) {
    mxmDepth = dep;
    indx = node;
  }
  for (auto child : graph[node]) {
    if (vis[child.first]) {
      cycle = true;
      return;
    }
    mnmDiameter = min(mnmDiameter, child.second);
    dfs(child.first, dep + 1);
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> edges;
  set<int> st;
  for (int i = 1; i <= n; i++) st.insert(i);
  for (int i = 1; i <= edges; i++) {
    int u, v, c;
    cin >> u >> v >> c;
    graph[u].push_back({v, c});
    st.erase(v);
  }
  vector<pair<int, pair<int, int>>> ans;
  for (auto par : st) {
    if (graph[par].empty()) continue;
    cycle = false;
    mxmDepth = 0;
    mnmDiameter = 1e9;
    indx = -1;
    dfs(par, 0);
    if (cycle) continue;
    ans.push_back({par, {indx, mnmDiameter}});
  }
  cout << ans.size() << "\n";
  for (auto it : ans) {
    cout << it.first << " " << it.second.first << " " << it.second.second
         << "\n";
  }
  return 0;
}
