dijkstra算法的优化,利用优先队列

#include <stdio.h>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define maxn 100000
#define INF 2147483647
struct edge{
  int to;
  int cost;
};//the side
typedef pair<int,int> p;//first is dijkstra second is top
priority_queue<p,vector<p>,greater<p> >que; //the min dijkstra first
vector<edge>G[maxn];//save the side from i
int dis[maxn];//save the dijkstra
void dijkstra(int c,int a)// c is begin a is the number of top;
{
  for(int i=0;i<=a;i++)//vector clear
    G[i].clear();
  while(!que.empty())//que clear
    que.pop();
  for(int i=0;i<=a;i++)
  {
    dis[i]=INF;
  }
  dis[c]=0;
  s.first=0;
  s.second=c;
  que.push(s);
  edge e;
  while(!que.empty())
  {
    p x=que.top();
    que.pop();
    int v=x.second;
    if(dis[v]<x.first)
      continue;
    for(int i=0;i<G[v].size();i++)
    {
      e=G[v][i];
      if(dis[e.to]>dis[v]+e.cost)
        {
          dis[e.to]=dis[v]+e.cost;
          s.first=dis[e.to];
          s.second=e.to;
          que.push(s);
        }
    }
  }
  for(int i=1;i<=a;i++)
}
int main()
{
  int t;
  cin>>t;
  while(t--)
  {
    int a,b,c,from,to,cost;
    p s;
    cin>>a>>b>>c;
    edge e;
    for(int i=0;i<b;i++)
    {
      cin>>to>>from>>cost;
      e.to=to;
      e.cost=cost;
      G[from].push_back(e);
    }
    dijkstra(c,a);
    for(int i=1;i<=a;i++)
        cout<<dis[i]<<" ";
  }
}


猜你喜欢

转载自blog.csdn.net/qq_30754565/article/details/80974717
今日推荐