# @author: Nikolaus Funk
# @date: 19:12:15
# Evaluation of the HashCode2019 Solutions

# Parses the given solution for a problem
#	@param:
#		file_path ... the given path to the file, specifying the content of the slides
#	@return:
#		slides    ... the pictures used in the order of slides given
def parse_solution(file_path):
	with open(file_path, 'r') as file:
		n = int(file.readline().strip().split()[0])
		slides = n*[0]
		line = file.readline().strip().split()
		
		for i in range(n):
			if len(line) == 1: slides[i] = [int(line[0])]
			else: slides[i] = [int(line[0]),int(line[1])]
			line = file.readline().strip().split()
	return slides


# Parses the input of the challenge
#	@param:
#		file_path ... The path to the file, specifying the tags of the pictures
#	@return:
#		pics      ... The list of pictures with their orientation and tags
def parse_input(file_path):
	with open(file_path, 'r') as file:
		n = int(file.readline().strip().split()[0])
		pics = n*[0]
		
		line = file.readline().strip().split()
		
		for i in range(n):
			orient = line[0]
			tags = int(line[1])*[0]
			for j in range(int(line[1])):
				tags[j] = line[2+j]
			pics[i] = (orient,tags)
			line = file.readline().strip().split()
	return pics


# Calculates the score of the given pair of slides
#	@param:
#		slide1 ... The tags of the first slide
#		slide2 ... The tags of the next slide
#	@return:
#		metric ... The score as specified by the challenge
def metric(slide1,slide2): # only the tags
	# 1. Number of similar
	# 2. Number of diff in S1
	# 3. Number of diff in S2
	l1 = set(slide1)
	l2 = set(slide2)
	d1 = len(l1-l2)
	d2 = len(l2-l1)
	metric = min(d1,d2,len(slide1)-d1)
	return metric


# Evaluates the given Solution on the problem instance
#	@param:
#		input_path    ... the path to the problem specification
#		solution_path ... the path to the generated solution
#	@return:
#		score         ... the sum of the metric of the given order of slides
def evaluate(input_path,solution_path):
	inp = parse_input(input_path)
	sol = parse_solution(solution_path)
	
	score = 0
	tags_cur = []
	if len(sol[0]) == 2:
		tags_cur = list(set(inp[sol[0][0]][1] + inp[sol[0][1]][1]))
	else:
		tags_cur = inp[sol[0][0]][1]

	for i in range(len(sol)-1):
		tags_next = []
		if len(sol[i+1]) == 2:
			tags_next = list(set(inp[sol[i+1][0]][1] + inp[sol[i+1][1]][1]))
		else:
			tags_next = inp[sol[i+1][0]][1]
		score += metric(tags_cur,tags_next)
		tags_cur = tags_next

	return score


# TEST INSTANCE
#print(evaluate('a_example.txt','a_solution.txt'))

