#include <bits/stdc++.h>
using namespace std;
void mad(long long &a, long long b) {
  a = (a + b) % 1000000007;
  if (a < 0) a += 1000000007;
}
long long gcd(long long a, long long b) {
  if (a > b) swap(a, b);
  if (!a) return b;
  return gcd(b % a, a);
}
pair<int, int> p[1005], s[1005];
int vis[1005];
int n;
pair<int, int> res[1005];
void solve() {
  int m;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int u, v, d;
    cin >> u >> v >> d;
    p[v] = pair<int, int>(u, d);
    s[u] = pair<int, int>(v, d);
  }
  int c = 0;
  for (int i = 0; i < n; i++) {
    if (p[i + 1].second == 0) {
      int j = i + 1;
      int mini = 1e9;
      while (s[j].second != 0) {
        mini = min(mini, s[j].second);
        j = s[j].first;
      }
      res[i + 1] = pair<int, int>(j, mini);
    }
  }
  for (int i = 0; i < n; i++)
    if (res[i + 1].second != 0 && res[i + 1].first != i + 1) c++;
  cout << c << "\n";
  for (int i = 0; i < n; i++)
    if (res[i + 1].second != 0 && res[i + 1].first != i + 1)
      cout << i + 1 << " " << res[i + 1].first << " " << res[i + 1].second
           << "\n";
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int t;
  t = 1;
  while (t--) {
    solve();
  }
}
