Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import defaultdict
- def get_map(file_path):
- """
- Read the mapping file and build a dictionary where each node maps to a
- dictionary of connected nodes with integer weights (1 by default).
- After loading, simplify the map by propagating vector values except for
- specific protected nodes.
- """
- output = {}
- for line in open(file_path).read().strip().split('\n'):
- left, right = line.strip().split(': ')
- df = defaultdict(int)
- for x in right.split(' '):
- df[x] = 1
- output[left] = df
- # Simplification stage
- for source_node, vector in tuple(output.items()):
- if source_node in ('svr', 'dac', 'fft'):
- continue
- for target_node, base in output.items():
- output[target_node] = compute_vector(source_node, base, vector)
- del output[source_node]
- return output
- def compute_vector(node, base, vector):
- """
- Compute the propagation effect of removing a node from a base vector:
- - If node is not in the base, return base unchanged.
- - Multiply the vector by the factor found in base[node].
- - Remove node from base and add the multiplied vector.
- """
- if node not in base:
- return base
- factor = base[node]
- del base[node]
- multiplied = {k: v * factor for k, v in vector.items()}
- for k, v in multiplied.items():
- base[k] += v
- return base
- def rec(path, power=1):
- """
- Recursive traversal through the computed map.
- Accumulate global total when a valid path to 'out' is reached
- containing both 'dac' and 'fft'.
- """
- global total
- node = path[-1]
- if node == 'out':
- if 'dac' in path and 'fft' in path:
- total += power
- return True
- return
- for nxt, p in mapping[node].items():
- rec(path + (nxt,), power * p)
- def main():
- """
- Main execution entry: performs the recursive enumeration of paths.
- """
- rec(('svr',))
- if __name__ == "__main__":
- print('\n' * 10)
- total = 0
- mapping = get_map('input.txt')
- main()
- print('solution:', total)
Advertisement
Add Comment
Please, Sign In to add comment