""" Google Code Jam Farewell Round C - Problem D Author : chaotic_iak Language: PyPy (Python 3.9.10) """ ################################################### SOLUTION def initialize_solution(): ... class DSU(): def __init__(self): self.parent = dict() self.rank = dict() def make(self, x): if x not in self.parent: self.parent[x] = x self.rank[x] = 0 def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) return self.parent[x] else: return x def merge(self, x, y): x = self.find(x) y = self.find(y) if x == y: return if self.rank[x] < self.rank[y]: x,y = y,x self.parent[y] = x if self.rank[x] == self.rank[y]: self.rank[x] += 1 def __repr__(self): return "" def main(): N,M,Q = read() edges = [read() for _ in range(M)] queries = [read() for _ in range(Q)] ans = 0 # components sets = DSU() for i in range(1,N+1): sets.make(i) for u,v,k in edges: sets.merge(u,v) components = dict() compedges = dict() compqueries = dict() for i in range(1,N+1): parent = sets.find(i) if parent not in components: components[parent] = [] compedges[parent] = dict() compqueries[parent] = [] components[parent].append(i) for u,v,k in edges: parent = sets.find(u) if k not in compedges[parent]: compedges[parent][k] = [] compedges[parent][k].append((u,v)) for u,v in queries: pu = sets.find(u) pv = sets.find(v) if pu == pv: compqueries[pu].append((u,v)) for com in components: if len(compedges[com]) % 2 == 1: ans += len(compqueries[com]) continue for k in compedges[com]: ccomp = DSU() for i in components[com]: ccomp.make(i) for kk in compedges[com]: if kk == k: continue for u,v in compedges[com][kk]: ccomp.merge(u,v) for i in range(len(compqueries[com])): if compqueries[com][i] == 0: continue u,v = compqueries[com][i] pu = ccomp.find(u) pv = ccomp.find(v) if pu == pv: ans += 1 compqueries[com][i] = 0 return ans ############################################### PROBLEM TYPE HAS_TESTCASES = True INTERACTIVE = False INTERACTIVE_WRONG_ANSWER = "" #################################################### HELPERS import sys def read_str(): ipt = input().strip() if INTERACTIVE and ipt == INTERACTIVE_WRONG_ANSWER: sys.exit() return ipt def read(mapping=int): ipt = input().strip() if INTERACTIVE and ipt == INTERACTIVE_WRONG_ANSWER: sys.exit() return list(map(mapping, ipt.split())) def write_str(obj, end="\n"): global OUTPUT OUTPUT.append(obj + end) def write(*obj, sep=" ", end="\n"): global OUTPUT OUTPUT.append(sep.join(map(str, obj)) + end) def flush(): global OUTPUT print("".join(OUTPUT), end="", flush=True) OUTPUT = [] def solve_testcase(): result = main() if result is not None: write(result) OUTPUT = [] initialize_solution() if HAS_TESTCASES: TOTAL_CASES = int(input()) else: TOTAL_CASES = 1 for CASE_NUMBER in range(TOTAL_CASES): write("Case #" + str(CASE_NUMBER+1) + ": ", end="") solve_testcase() flush() READ_FROM_FILE = ""