class BIT
	def initialize a
		@b = [*a]
		(1..@b.size).each{|i|
			j = i+(i&-i)
			@b[j-1] += @b[i-1] if j<=@b.size
		}
	end

	def [] i
		v,i = 0,i+1
		v,i = v+@b[i-1],i-(i&-i) while 0<i
		return v
	end

	def dec i
		i += 1
		while i<=@b.size
			@b[i-1] += 1
			i += i&-i
		end
	end
end

puts gets.to_i.times.map{
	n = gets.to_i
	klr = n.times.map{ gets.split.map(&:to_i) }
	嬉,ls,rs = 0,BIT.new(0..n),BIT.new(0..n)
	klr.sort_by{|_,l,r| (l-r).abs }.reverse_each{|lk,l,r|
		if l==r
			嬉 += l
		else
			k,s,hi,lo = l<r ? [n-lk,rs,r,l] : [lk,ls,l,r]
			sk = s[k]
			if 0<sk
				嬉 += hi
				s.dec (1..k).bsearch{|i| s[i]<=sk }
			else
				嬉 += lo
			end
		end
	}
	next 嬉
}
