#include <bits/stdc++.h>
using namespace std;
struct node {
  node* next;
  node* prev;
  int num;
  int inP;
  int outP;
};
void check(node* first, int min, int arr[][3], int i) {
  if (first->inP == -1) arr[i][0] = first->num;
  if (first->outP == -1) arr[i][1] = first->num;
  if (first->outP != -1) {
    if (arr[i][2] > first->outP) arr[i][2] = first->outP;
    check(first->next, arr[i][2], arr, i);
  }
}
int main() {
  int N, P, i;
  cin >> N >> P;
  node* house[1011];
  for (i = 0; i < N; i++) house[i] = new node;
  for (i = 0; i < N; i++) {
    house[i]->inP = -1;
    house[i]->outP = -1;
    house[i]->num = i + 1;
    house[i]->next = NULL;
    house[i]->prev = NULL;
  }
  int a, b, d;
  for (i = 0; i < P; i++) {
    cin >> a >> b >> d;
    house[a - 1]->outP = house[b - 1]->inP = d;
    house[a - 1]->next = house[b - 1];
    house[b - 1]->prev = house[a - 1];
  }
  int counter = 0;
  int arr[1002][3];
  for (i = 0; i < 1002; i++) arr[i][0] = 0;
  for (i = 0; i < N; i++) {
    if (house[i]->inP == -1 && house[i]->outP != -1) {
      arr[counter][2] = house[i]->outP;
      check(house[i], house[i]->outP, arr, counter);
      counter++;
    }
  }
  cout << counter << endl;
  for (i = 0; i < counter; i++) {
    cout << arr[i][0] << " " << arr[i][1] << " " << arr[i][2] << endl;
  }
  return 0;
}
