#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <map>
using namespace std;
const int maxn = 100010;
const int mod = 10007;
typedef pair<int,int> Pair;
vector<Pair> a, b;
int color[maxn];
int t, n, i, j, colors, aa, bb, t1, t2, ans, maxedge, edge, cnt;
int main()
{
    //freopen("e.in", "r", stdin);
    while (scanf("%d", &n), n>0)
    {
        a.clear(); b.clear();
        for (i = 0; i < n; i++)
        {
            scanf("%d%d%d%d", &aa, &t1, &bb, &t2);
            a.push_back(make_pair(aa, t1));
            b.push_back(make_pair(bb, t2));
        }
        memset(color,0,sizeof(color));
        colors = 0; ans = 1;
        for (i = 0; i < n; i++)
        if (color[i] == 0)
        {
            colors++;
            j = a[i].first; maxedge = a[i].second; cnt = 1;
            bool first = true;
            do {
                color[j] = colors;
                if (color[a[j].first]==0 && (a[j].first!=i || !first)) {
                    edge = a[j].second;
                    j = a[j].first;
                } else
                if (color[b[j].first]==0 && (b[j].first!=i || !first)) {
                    edge = b[j].second;
                    j = b[j].first;
                } else break;
                first = false;
                if (edge > maxedge)
                {
                    maxedge = edge;
                    cnt = 1;
                } else
                if (edge == maxedge) cnt++;
            } while (j != i);
            ans = (ans*cnt)%mod;
        }
        printf("%d\n", ans);
    }
    return 0;
}