#include <bits/stdc++.h>
using namespace std;
const long double EPS = 1E-9;
const int INF = (int)1E9;
const long long INF64 = (long long)1E18;
vector<pair<long long, int> > v[1001];
bool vis[1001] = {0};
struct s {
  int a, b, c;
};
vector<s> ans;
bool dfs(int a, int b, int d) {
  if (v[a].size() == 0) {
    s ob;
    ob.a = b + 1;
    ob.b = a + 1;
    ob.c = d;
    ans.push_back(ob);
    return 0;
  }
  vis[a] = 1;
  for (int i = 0; i < (int)(v[a].size()); i++) {
    if (vis[v[a][i].first] == 0) dfs(v[a][i].first, b, min(d, v[a][i].second));
  }
}
bool operator<(s ob1, s ob2) {
  if (ob1.a < ob2.a) return 1;
  return 0;
}
int main() {
  int n, p;
  cin >> n >> p;
  map<int, int> m;
  for (int i = 0; i < (int)(p); i++) {
    int x, y, z;
    cin >> x >> y >> z;
    x--, y--;
    m[x]++, m[y]++;
    v[x].push_back(make_pair(y, z));
  }
  for (int i = 0; i < (int)(n); i++) {
    if (vis[i] == 0 && v[i].size() == 1 && m[i] == 1) {
      dfs(i, i, v[i][0].second);
    }
  }
  sort(ans.begin(), ans.end());
  cout << ans.size() << endl;
  for (int i = 0; i < (int)(ans.size()); i++)
    cout << ans[i].a << " " << ans[i].b << " " << ans[i].c << endl;
}
