Solution: This problem can be abstracted into a directed graph, through topological sorting to determine whether there are loops in the graph, if there are loops, the output "LOOP", if there are no loops, the output of each device is calculated by the results of topological sorting.
1. Topological Ordering Ideas:
(1) Define a queue Q and add all nodes with 0 to the queue.
(2) Take out the first node of the team and output. Then delete all edges from it, and make the vertices that reach them -1, and if the entry of a vertex is reduced to 0, it is queued.
(3) Repeat operation (2) until the queue is empty. If the queue is empty, the number of nodes that have been in the queue is exactly N (the total number of nodes in the figure), indicating that the topology is successfully sorted. Otherwise, the topology sort fails with rings in the diagram.
3. How do I record the input of each device?
(including the input signal connected to the device and the output result of the previous device)
Here we define the input of each device as a string type, use the substr() function to cut the string, get the first character of the input, and determine whether it is 'I' or 'O':
Again, the substr() function is used to obtain the number after I/O in the input string, that is, the number of the input signal or the number of the previous device connected to the device. Use the atoi(string.c_str()) method to convert the obtained numeric characters from string to int.
To determine whether the input of the device is of type 'I' or type 'O', the input signal number or the number of the previous gate device connected to the gate is added to the gate device structure by using the push_back() method according to the disadvantage of the type. In the case of the 'O' type, it is also necessary to store the gate device number and the previous gate device number connected to the gate in the adjacency table.