如果我没听错的话,有起点城市和终点城市,我们需要找到以最少航班从起点城市到达目的地城市的方式。那样可以么?
我如何看待动态规划的解决方案,让我们可以使用仅使用航班dp[i][j]
到达城市的最佳时间。一开始,所有元素都设置为。我们将尝试在每一步更新它。因此,算法将如下所示:i
j
dp
infinity
dp[0][0] = 0;
priority_queue< pair<int,int> > q;
q.Add( make_pair(0,0) );
/*in q we store pair, where first is time of arrival in city,
and the second is THAT city.*/
while there are element is queue {
x = the first one element ( where time is the smallest )
remove first element from queue
if x.city == destination city
break cycle;
then
for all j
if dp[x.city][j] < x.time + 50
for all flights(from, to) where from==x.city we try to update
if( dp[to][j+1] < dp[x.city][j] + 50 + jurney_duration ) {
dp[to][j+1] = dp[x.city][j] + 50 + jurney_duration ;
q.add( make_pair(dp[x.city][j] + 50 + jurney_duration, to) );
}
}
所以,要找到答案,我们只需要找到最小的x
where dp[final_dest][x] != infinity
,这x
就是答案。
效率将是O(n*n*m)
,因为while-cycle
我们的主体只会运行n
次数( where n - number of cities
),而循环有两个循环n
和m
。我们将for-cycle
仅先运行 n 次,因为该路径将使用少于N
航班 - 没有理由返回您之前所在的城市。
编辑:
实际上,如果我们将像邻接列表这样的航班信息存储起来,我们可以获得更好的效率:O(n*m),因为例如,如果编号为 m 的城市与m ii
相邻,我们将得到 N*m 0 + N*m 1 + ... + N*m N = N*(m 0 + m 1 + ... + m n ) = N*M,因为 m i th 的总和 == M. (M 代表航班总数)。
有关优先级队列的更多详细信息