简体   繁体   中英

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). Although it seems that the running time of this algorithm is same as Dijkstra but I think it is different. 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.

 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.

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.

I believe that is the only part which is changed from the original Dijkstra algorithm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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