#include <bits/stdc++.h>
#define rep(i,n) for (int i=0; i<(n); ++i)
using namespace std;
typedef long long ll;
typedef pair<int,int> P;

int n,a[1010][1010],h[1000100],dist[1000100];
vector<int>to[1000100];

int encode(int i, int j){
  if(i>j)swap(i,j);
  return i*n+j;
}

int main(){
  cin>>n;
  rep(i,n)rep(j,n-1){
    cin>>a[i][j];
    a[i][j]--;
  }
  rep(i,n)rep(j,n-2){
    int v=encode(i,a[i][j]);
    int u=encode(i,a[i][j+1]);
    to[v].push_back(u);
    h[u]++;
  }
  stack<int>st;
  rep(i,n*n)if(h[i]==0)st.push(i),dist[i]=1;
  while(st.size()){
    int v=st.top(); st.pop();
    for(int u:to[v]){
      h[u]--;
      if(h[u]==0)st.push(u);
      dist[u]=max(dist[u],dist[v]+1);
    }
  }
  int mx=0,in=0;
  rep(i,n*n)mx=max(mx,dist[i]);
  rep(i,n*n)in=max(in,h[i]);
  if(in!=0)cout<<-1<<endl;
  else cout<<mx<<endl;
}
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cassert>
#include <iostream>
#include <sstream>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <utility>
#include <numeric>
#include <algorithm>
#include <bitset>
#include <complex>
#include <array>
#include <list>
#include <stack>
#include <valarray>

using namespace std;

typedef unsigned uint;
typedef long long Int;
typedef unsigned long long UInt;

const int INF = 1001001001;
const Int INFLL = 1001001001001001001LL;

template<typename T> void pv(T a, T b) { for (T i = a; i != b; ++i) cout << *i << " "; cout << endl; }
template<typename T> void chmin(T& a, T b) { if (a > b) a = b; }
template<typename T> void chmax(T& a, T b) { if (a < b) a = b; }
int in() { int x; scanf("%d", &x); return x; }
double fin() { double x; scanf("%lf", &x); return x; }
Int lin() { Int x; scanf("%lld", &x); return x; }

Int P[5050];
pair<int, int> A[5050];

int main() {
  int N = in();
  P[0] = 0;
  for (int u = 1; u <= N; ++u) {
    P[u] = INFLL;
  }
  for (int i = 0; i < N; ++i) {
    A[i].first = in();
    A[i].second = in();
  }
  sort(A, A + N, [] (const pair<int, int>& a, const pair<int, int>& b) {
    return a.first + a.second < b.first + b.second;
  });

  for (int i = 0; i < N; ++i) {
    int H = A[i].first;
    int Z = A[i].second;
    for (int u = i; u >= 0; --u) {
      if (P[u] <= H) {
        chmin(P[u + 1], P[u] + Z);
      }
    }
  }

  int res = 0;
  for (int u = 0; u <= N; ++u) {
    if (P[u] < INFLL) {
      chmax(res, u);
    }
  }
  printf("%d\n", res);

  return 0;
}
