def contact(a,b)
	ax,ay,bx,by = a
	cx,cy,dx,dy = b
	d = (bx-ax)*(dy-cy)-(by-ay)*(dx-cx)
	acx = cx-ax
	acy = cy-ay
	if d == 0
		nil
	else
		r = ((dy-cy)*acx-(dx-cx)*acy)/d
		s = ((by-ay)*acx-(bx-ax)*acy)/d
		if (0.0..1.0).include? r and (0.0..1.0).include? s
			[ax+(bx-ax)*r,ay+(by-ay)*r]
		else
			nil
		end
	end
end

gets.to_i.times {
	line = gets.split(" ").map(&:to_f)
	p Enumerator.new {|y|
		sx,sy = line
		gets.to_i.times {
			rail = gets.split(" ").map(&:to_f)
			if !(p = contact(rail,line)).nil?
				dx , dy = p
				_,_,_,_,o,l = rail
				arr = [[1,0],[0,1]]
				y << [(sx-dx)**2 + (sy-dy)**2,arr[o][l]]
			end
		}
	}.sort {|a,b|
		a[0] <=> b[0]
	}.each_cons(2).count {|a,b|
		a[1]!=b[1]
	}
}