### constant

MOD = 10007

### main

loop do
  n = gets.to_i
  break if n == 0

  nbrs = n.times.map{[]}
  edges = n.times.map{{}}

  for i in (0...n)
    j0, f0, j1, f1 = gets.split.map(&:to_i)
    nbrs[i] = [j0, j1]
    
    if nbrs[j0].include?(i)
      edges[i][j0] = edges[j0][i] = f0
    end

    if nbrs[j1].include?(i)
      edges[i][j1] = edges[j1][i] = f1
    end
  end
  #p edges

  used = n.times.map{false}
  count = 1

  for ri in (0...n)
    next if used[ri]

    prj = ri
    rj = nbrs[ri][0]
    used[ri] = used[rj] = true

    max_f = edges[ri][rj]
    max_n = 1

    loop do
      rj1 = (prj == nbrs[rj][0]) ? nbrs[rj][1] : nbrs[rj][0]
      f = edges[rj][rj1]

      if max_f < f
        max_f = f
        max_n = 1
      elsif max_f == f
        max_n += 1
      end

      break if rj1 == ri

      prj = rj
      rj = rj1
      used[rj] = true
    end

    count = (count * max_n) % MOD
  end

  puts count
end