SQL tree data struct(7): find the minimal cost route



-- find the minimal cost route

create table flights(departure char(20), destination char(20), cost int)
insert flights
select 'Chicago', 'New York', 10 union
select 'Chicago', 'Milwaukee', 20 union
select 'Denver', 'Chicago', 25 union
select 'Seattle', 'Chicago',30 union
select 'Seattle', 'Denver',40 union
select 'Seattle', 'San Francisco', 50 union
select 'Milwaukee', 'Seattle',11 union    -- cycle 1: to the first source
select 'Milwaukee', 'Michigan', 36 union
select 'Milwaukee', 'Denver', 9 -- cycle 2: to the intermediate source

/*
insert into flights select destination, departure, cost from flights

select * from flights
*/

if object_id('mincostroute') is not null
    drop procedure mincostroute
go

create procedure mincostroute(@from char(20), @to char(20))
with encryption
as
declare @depth int, @hasmore int
select @depth = 0, @hasmore = 1

/* can not use table variable, a table-var can not refer : table-var.field */
select top 0 src=replicate('.',20), dst=replicate('.',20), stops=0, route=replicate('.', 4000), ttlcost=0
    into #map from sysfiles1

insert into #map select '', @from, @depth, @from, 0

while @hasmore > 0
begin
    select @depth = @depth + 1

    insert into #map
    select flights.departure, flights.destination, @depth,
        #map.route + '->' + destination, ttlcost+cost
    from #map inner join flights on #map.dst = flights.departure
    where stops = @depth-1 and flights.destination not in (select src from #map)
    set @hasmore = @@rowcount
end

--select * from #map

--select * from #map where dst = @to
select top 1 route=rtrim(route), ttlcost from #map where dst = @to order by ttlcost asc

drop table #map
go

exec mincostroute 'Seattle', 'Michigan'
drop table flights
drop proc mincostroute
go
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值