电路板问题

来源:互联网 发布:豆瓣怎么做淘宝 编辑:程序博客网 时间:2024/05/17 09:24

There are n terminals on each side of a circuit board indexed with 1, 2, …, n from left to right, as shown in the following figure. We need to connect terminal i (1 ≤ in) on the top side with a unique terminal π(i) on the bottom side, and vice versa. In other words, we need n lines (i, π(i)) (1 ≤ in) to connect n pairs of terminals,.

Two lines (i, π(i)) and (j, π(j)) ( i ¹ j) will cross each other if i < j but π(i) > π(j), or vice versa. Two lines are called compatible if they do not cross each other. We wish to find the largest set of mutually compatible lines so that they can be layout on the same layer of circuit without crossing each other.

 

Please model this problem as a graph problem first and then design an O(n2) algorithm to solve it.

 

Solution:

 

We construct a directed graph G(V, E) as follows.

(1)   For each line (i, π(i)) (1 ≤ in), we construct a vertex vi.

(2)   If lines (i, π(i)) and (j, π(j)) ( i < j) are compatible, then draw an edge from vi to vj.

(3)   Add one vertex s to V, so V = {s} È { v1, v2, v3, ...., vn }.

(4)   Draw an edge from s to each vi (1 ≤ in).

 

It is easy to see that lines with indices i1 < i2 < i3 < .... < vk are mutually compatible if and only if there is a path <s, v1, v2, v3, ...., vk>. Therefore, the longest path in G corresponds to the largest compatible set. We can use the algorithm in problem 3 to find the longest path in G.

 

The time complexity is O(n2) because we may check every pair of lines when we construct the graph G. Finding the longest path needs O(n+m) = O(n2) time in the worst case.

原创粉丝点击