简体   繁体   中英

Efficient algorithm to check queue consistency by pairwise relationship

We have n items entering and leaving a queue, they could enter and leave at any time. The information we have is that for each pair (a,b), we know either 1) a leaves the queue before b enters or vice versa; 2) at some point, a and b are in the queue at the same time. or 3) no information at all. Suppose we are given a list of pairwise information for all (n choose 2) pairs, find a O(n^2) algorithm to determine if there is any inconsistency in the information.

For example, a leaves before b enters(for simplicity, write it as a>b), b>c, and c=a is inconsistent, since there is no possible timeline of a,b,c to enter and leave the queue that makes all three statements true. I thought about making this a graph transversal problem, each item as a vertex, pairwise relation as an edge, if a>b or b<a then it's a directed edge, if a=b then it's an undirected edge, then this problem may be reduced to some sort of cycle detection in a mixed graph (with directed or undirected edges), where algorithms such as DFS or BFS can be applied. However, it's not just any kind of cycle leads to inconsistency, obviously if all edges in the cycle are directed, then it's inconsistent for sure, as > or < is transitive. However, if all edges in a cycle are undirected, there is no inconsistency. Or if some are directed or some are undirected, could be either inconsistent or consistent. For example, a>b, b>c, and c=a is inconsistent, while a=b,b=c and c>a is consistent.

Any input and idea will be greatly appreciated!

Think of this as a digraph, where there's an arc from a to b if a leaves before b enters, and vice versa.

For nodes (x,y) that are in the queue at the same time, note that this means that for every vertex w, a consistent graph doesn't have x < w < y, and also doesn't have x > w > y. Reflect this by merging such nodes into a single node, preserving all arcs.

Then, run a topological sort to find a topological ordering of the nodes.

There's an inconsistency if and only if there's no topological ordering.

Running time: topo sort is O(nodes + edges) which is O(n^2).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM