這個算法相當簡單。首先,使用 fares 表中的數據填充 faretemp 表,作為初始的航程。然后,取到我們剛才插入的所有數據,使用它們建立所有可能的二航程(two-hop)路徑。重復這一過程,直至在兩個節點之間創建了新路徑。 循環過程將在節點間所有可能的路徑都被描述之后退出。假如我們只對某個開始條件感愛好,那么我們還可以限制第一次的插入從而減少裝載數據的量。下面是發現路徑的代碼:truncate table faretemp;
begin
-- initial connections
insert into faretemp
select depart,arrive,1,depart','arrive,PRice from fares;
while sql%rowcount > 0 loop
insert into faretemp
select depart,arrive,hops,route,price from nexthop
where (depart,arrive)
not in (select depart,arrive from faretemp);
end loop;
end;
/
show errors;select * from faretemp order by depart,arrive; 可以在表 A 中查看輸出。 前面的數據有一個小問題。數據是點之間最短路徑(最小航程數)的集合。然而,從倫敦到圣保羅的航程卻不是最便宜的一個。 要解決最便宜的費用問題,需要對我們的循環做一個改進,當在一個航程中發現一個更便宜的路線時使用這個路線代替原來的路線。修改后的代碼如下:truncate table faretemp;
declare
l_count integer;
begin
-- initial connections
insert into faretemp
select depart,arrive,1,depart','arrive,price from fares;
l_count := sql%rowcount;
while l_count > 0 loop
update faretemp
set (hops,route,price) =
(select hops,route,price from nexthop
where depart = faretemp.depart
and arrive = faretemp.arrive)
where (depart,arrive) in
(select depart,arrive from nexthop
where price < faretemp.price);
l_count := sql%rowcount;
insert into faretemp
select depart,arrive,hops,route,price from nexthop
where (depart,arrive)
not in (select depart,arrive from faretemp);
l_count := l_count + sql%rowcount;
end loop;
end;
/
show errors;
select * from faretemp order by depart,arrive; 可能在表 B 中查看輸出。 算法發現LHR、JFK、GRU 路線比 LHR、GRU 路線便宜,所以用前者代替了后者。循環將在沒有更便宜的費用,并且沒有其它可能路線時退出。