#include<iostream>
#include<queue>
#include<vector>
using namespace std;

struct Edge{
  int src,dst,weight;
  Edge(int src,int dst,int weight) : src(src), dst(dst), weight(weight) { }
};

typedef vector<Edge> Edges;
typedef vector<Edges> Graph;

int bfs(Graph &g) {
  int n = g.size();
  vector<int> done(n, 0);

  int ans = 1;
  for(int i=0; i<n; ++i) {
    if(done[i] != 0) continue;
    queue<Edge> q;
    int cost = 0,st = 0;
    done[i] = 1;
    for(q.push(g[i][0]),q.push(g[i][1]);!q.empty();) {
      Edge e = q.front();
      q.pop();
      if(e.weight>cost) cost = e.weight;
      if(done[e.dst] != 0) continue;
      done[e.dst] = 1;
      q.push(g[e.dst][0]);
      q.push(g[e.dst][1]);
    }

    for(int i=0; i<n; ++i) {
      if(done[i]==1 && g[i][0].weight == cost)
	st++;
      if(done[i]==1 && g[i][1].weight == cost)
	st++;
      if(done[i]==1)
	done[i] = 2;
    }

    st /= 2;
    ans *= st;
    ans %= 10007;
  }
  return ans;
}

int main() {
  int n;
  while(cin>>n, n) {
    Graph g(n);
    int b1,b2,f1,f2;
    for(int i=0; i<n; ++i) {
      cin>>b1>>f1>>b2>>f2;
      g[i].push_back( Edge(i, b1, f1) );
      g[i].push_back( Edge(i, b2, f2) );
    }
    cout<<bfs(g)<<endl;
  }
}