list-sort

A certain business maintains a list of all its customers' names. The list is arranged in order of importance, with the last customer in the list being the most important. Now, he want to create a new list sorted alphabetically according to customers' last names, but among customers with the same last name he want the more important ones to appear earlier in the new list. Alphabetical order (and equality of last names) should not be case sensitive.

Input:-
First line contains no. of test cases and first line of each test case contains n i.e. no. of elements and next n lines contains contains a name.

Output:- Print the new list with each element in a new line.

SAMPLE INPUT
2
5
Tom Jones
ADAMS
BOB ADAMS
Tom Jones
STEVE jONeS
3
Trudy
Trudy
TRUDY

SAMPLE OUTPUT
BOB ADAMS
ADAMS
STEVE jONeS
Tom Jones
Tom Jones
TRUDY
Trudy
Trudy

Source: hackerearth | Difficulty: UNKNOWN_DIFFICULTY


Solutions:
for _ in range(eval(input())):
	dic={}
	n=eval(input())
	list=[]
	list1=[]
	list3=[]
	last=[]
	for i in range(n):
		x=input().split()
		z=len(x)
		if x[z-1].lower() not in last:
			last.append(x[z-1].lower())
		try:dic[x[z-1].lower()].append(x)
		except:
			dic[x[z-1].lower()]=[]
			dic[x[z-1].lower()].append(x)
	last.sort()
	for i in last:
		for j in reversed(dic[i]):
			for c in j:
				print(c, end=' ')
			print("")	
			

	
		
		


if __name__=='__main__':
	T = int(input())
	for _ in range(T):
		n = int(input())
		memo={}
		last = []
		for i in range(n):
			x = list(map(str,input().split()))
			z = len(x)
			if x[z-1].lower() not in last:
				#print("gg",x[z-1].lower())
				last.append(x[z-1].lower())
			try:memo[x[z-1].lower()].append(x)
			except:
				memo[x[z-1].lower()]=[]
				memo[x[z-1].lower()].append(x)
		last.sort()
		for i in last:
			for j in reversed(memo[i]):
				for c in j:
					print(c, end=' ')
				print()
		#print(memo)


'''
# Read input from stdin and provide input before running code

name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''

def fun(l):
	a=[]
	
	b=l[::-1]
	for j in range(len(b)):
		s=b[j].split(" ")
		if(len(s)>=2):
			a.append([s[-1].lower(),j])
		else:
			a.append([s[0].lower(),j])
	
	a.sort(key=lambda tup: tup[0])
#	print(a)
	for i in a:
		print((b[i[1]]))

	
t=int(input())
for u in range(t):
	n=int(input())
	l=[]
	for i in range(n):
		l.append(input())
	
	fun(l)