#include <bits/stdc++.h>
using namespace std;
const int MAXN = 300, MAXK = 10;
int n, m, x, y, z, w, Ans;
int dp[MAXK + 5][MAXN + 5][MAXN + 5];
int tmp[MAXN + 5][MAXN + 5], now[MAXN + 5][MAXN + 5];
int main() {
  memset(now, 0xcf, sizeof(now));
  memset(dp, 0xcf, sizeof(dp));
  scanf("%d %d", &n, &m);
  for (int i = 1; i <= m; i++) {
    scanf("%d %d %d %d", &x, &y, &z, &w);
    dp[0][x][y] = z;
    dp[0][y][x] = w;
  }
  for (int i = 1; i <= n; i++) now[i][i] = 0, dp[0][i][i] = 0;
  for (int s = 1; s <= MAXK; s++)
    for (int k = 1; k <= n; k++)
      for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
          dp[s][i][j] = max(dp[s][i][j], dp[s - 1][i][k] + dp[s - 1][k][j]);
  for (int s = MAXK; s >= 0; s--) {
    memset(tmp, 0xcf, sizeof(tmp));
    for (int k = 1; k <= n; k++)
      for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
          tmp[i][j] = max(tmp[i][j], now[i][k] + dp[s][k][j]);
    bool f = 0;
    for (int i = 1; i <= n; i++)
      if (tmp[i][i] > 0) {
        f = 1;
        break;
      }
    if (f)
      continue;
    else {
      for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++) now[i][j] = tmp[i][j];
      Ans += 1 << s;
    }
  }
  printf("%d\n", Ans >= n ? 0 : Ans + 1);
  return 0;
}
