#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > graph[1001];
bool vis[1001];
vector<int> res;
int best = 1000000000;
int deg[1001];
void dfs(int node, int di) {
  vis[node] = true;
  best = min(best, di);
  for (int i = 0; i < graph[node].size(); i++) {
    if (!vis[graph[node][i].first]) {
      dfs(graph[node][i].first, graph[node][i].second);
    }
  }
  if (graph[node].size() == 0) res.push_back(node);
}
int main() {
  int n, p;
  memset(deg, 0, sizeof deg);
  cin >> n >> p;
  for (int i = 0; i < p; i++) {
    int from, to, dia;
    cin >> from >> to >> dia;
    deg[from]++, deg[to]++;
    graph[from].push_back(make_pair(to, dia));
  }
  if (p >= n) {
    cout << 0 << endl;
    return 0;
  }
  vector<pair<int, pair<int, int> > > result;
  for (int i = 1; i <= n; i++) {
    if (!vis[i] && deg[i] == 1 && graph[i].size() == 1) {
      dfs(i, 1000000000);
      if (res.size() == 1)
        result.push_back(make_pair(i, make_pair(res[0], best)));
      best = 1000000000;
      res.clear();
    }
  }
  cout << result.size() << endl;
  for (int i = 0; i < result.size(); i++)
    cout << result[i].first << " " << result[i].second.first << " "
         << result[i].second.second << endl;
}
