一. 匹配问题
PSL is a shipping company that owns n ships and provides service to n ports.Each ship has a schedule that says, for each day of the month (m(m > n) days), which of the ports it's currently visiting, or whether
it's out at sea. Each ship visits each port for exactly one day during the month. For safety reasons, PSL has
the following strict requirement:
(£) No two ships can be in the same port on the same day.
The company wants to perform maintenance on all the ships this month. In this case, each ship Si will
arrive in one scheduled port and simply remains there for the rest of the month (for maintenance).
This means that Si will not visit the remaining ports on its schedule (if any) that month.
Now the question is: given the schedule for each ship, find when each ship should stop its travel so
that condition (£) continues to hold. Try to give an algorithm to find the solution and analyse its time
complexity.
For example, there are 2 ships and 2 ports, and 4 days in this “month”.
If the schedule of the first ship is:
port P1 ; at sea; port P2 ; at sea
and the schedule of the second ship is:
at sea; port P1; at sea; port P2
then the only solution is to make the first ship stay in port P2 since the
third day, and the second ship stay in port P1 since the second day.
二.问题分析:
首先给了一个各个Ship的schedule表格,安排每个船的靠岸航海情况,并且要进行维修,就是给每个Ship找一个Port, 就是进行匹配的问题。
问题解决:
这个问题应用Gale-Shapley 算法,但稍微有些区别,将Ship 比作Man, Port 比作 Women,只是women没有了选择的权利,但是有day 的限制, 并且Ship后到Port的将有更多的权利可以占有这个Port。且每个Port不能同时有两个ship, 即对应的不能两个men,求婚成功同一个women。
维修匹配算法流程:
<pre name="code" class="cpp">for d = 1 to N do
day[d] = 0;
end for;
while TRUE do
If there is no ship s such that state[s] = NULL then
return;
end if
select such a ship s arbitrarily;
p = the next port on s’s schedule to whom s have not yet arrived;
if state[p] == NULL then
state[p] = s; state[s] = p;
else if the ship arrive the port day[s] > the state[p] arrive the port day[state[p]] then
state[state[p]] = NULL; state[p] = s; state[s] = p;
else
;//do nothing means simply find next port;
end if
end while
三.正确性证明:
1)在海上的ship就会寻找下个schedule 上的port,只要日期在当前已有ship后面就可停靠。
2)每个port 只要有ship, 就会一直保持有ship。
3)一个ship 停在了一个port, 还有可能被其他船占用。
可结束:
假设有个port没有ship, 则一定有个ship 并且已将停过此port 在sea 上,则它一定被替代了,或者还没有到这个port, 与算法流程不符。
时间复杂度:
与Gale-Shapley 算法一样是O(n^2) 。