简体   繁体   English

Dijkstra 算法的一种变体

[英]A variant of Dijkstra algorithm

I found this algorithm from CP3 book for ICPC, it is a variant of Dijkstra but it gives TLE in some cases (hidden tests).我从 ICPC 的 CP3 书中找到了这个算法,它是 Dijkstra 的一个变体,但在某些情况下它会提供 TLE(隐藏测试)。 Although it seems that the running time of this algorithm is same as Dijkstra but I think it is different.虽然看起来这个算法的运行时间与 Dijkstra 相同,但我认为它是不同的。 Can anyone help me with the time complexity of this algorithm.谁能帮我解决这个算法的时间复杂度。

 vector<int> visited(N,0),dis(N,0);
 vector<pair<int,int> > adj[N];        // value, node
 void dijkstra()                    
 {
     for(int i=2;i<=N;i++)
        dis[i]=N;
     priority_queue<pair<int,int> ,vector<pair<int,int> >,greater<pair<int,int> > > pq;
     pq.push(make_pair(0,1));
     while(!pq.empty())
     {
         pair<int,int> p=pq.top();
         ll x=p.second;
         pq.pop();
         if(p.first>dis[x])
             continue;
         for(int i=0;i<adj[x].size();i++)
         {
             if(dis[adj[x][i].ss]>dis[x]+adj[x][i].first)
             {
                 dis[adj[x][i].second]=dis[x]+adj[x][i].first;
                 pq.push(make_pair(dis[adj[x][i].second],adj[x][i].second));
             }
         }
     }
 }

Arrays in C++ are zero based, that is the first index is 0 and the last is size()-1. C++ 中的 Arrays 从零开始,即第一个索引为 0,最后一个索引为 size()-1。

 vector<int> visited(N,0),dis(N,0); <--- dis is initialized with N zero's
 vector<pair<int,int> > adj[N];        // value, node
 void dijkstra()                    
 {
     for(int i=2;i<=N;i++)
        dis[i]=N; <---- initializing i=N or dis[N] is undefined behaviour

You write beyond the end of the array with possible disastrous results.你写超出数组的末尾可能会导致灾难性的结果。 Your real error might be that that你真正的错误可能是

dis[1] = 0 

Where it should have been N or MAX_INT.它应该是 N 或 MAX_INT。

This algorithm can run infinitely when there exists a graph of a particular pattern.当存在特定模式的图形时,该算法可以无限运行。 p.first>dis[x] may not always be true and then it will not exit the loop. p.first>dis[x]可能并不总是true ,然后它不会退出循环。

I believe that is the only part which is changed from the original Dijkstra algorithm我相信这是从原始 Dijkstra 算法改变的唯一部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM