from math import inf def solve(N, D, C): incoming = [0] * N seen = set() cycles = [] for source in range(N): if source not in seen: path = [source] seen.add(source) while True: u = path[-1] v = D[u] incoming[v] += C[u] if v not in seen: path.append(v) seen.add(v) else: if v in path: i = path.index(v) cycle = path[i:] cycles.append(cycle) else: pass break ans = sum(max(0, C[x] - incoming[x]) for x in range(N)) for cycle in cycles: # Need to break cycle smallestIncrease = inf for x, y in zip(cycle, cycle[1:] + cycle[:1]): assert D[x] == y oldCost = max(0, C[y] - incoming[y]) newCost = max(0, C[y] - incoming[y] + C[x]) increase = newCost - oldCost smallestIncrease = min(smallestIncrease, increase) ans += smallestIncrease return ans if __name__ == "__main__": T = int(input()) for t in range(1, T + 1): (N,) = [int(x) for x in input().split()] D = [int(x) - 1 for x in input().split()] # 0 indexed C = [int(x) for x in input().split()] ans = solve(N, D, C) print("Case #" + str(t) + ": " + str(ans))