#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>
#include <cmath>

using namespace std;

void clearvector(vector< vector<int> >& v) {
    for (int i = 0; i < v.size(); i++) {
        v[i].clear();
    }
}

int findpos(vector<int> v, int value) {
    for (int i = 0; i < v.size(); i++) {
        if (v[i] == value) {
            return i;
        }
    }
    return -1;
}

vector< vector<int> > to(101); // each entry is a vector of all "next" points

int cyclelength(vector<int> trav, int next_place) {
    int pos = findpos(trav, next_place);
    int mx = -1;

    if (pos != -1) {
        return trav.size() - pos;
    } else {
        trav.push_back(next_place);
        for (int i = 0; i < to[next_place].size(); i++) {
            mx = max(mx, cyclelength(trav, to[next_place][i]));
            if (mx >= 0) return mx;
        }
    }
    return mx;
}

int main() {
    ifstream fin("DATA5.txt");
    ofstream fout("OUT5.txt");

    vector<int> emptyvec;
    vector<bool> traversed(101);

    for (int cc = 0; cc < 5; cc++) {
        clearvector(to);
        emptyvec.clear();
        int paths, from, tot;
        fin >> paths;

        for (int i = 0; i < paths; i++) {
            fin >> from >> tot;
            to[from].push_back(tot);
        }

        fout << cyclelength(emptyvec, 1) << endl;
    }
}

