Dijksrta&&Spfa

Dijkstra算法

void Dijkstra(ints)

{

      memset(mark,0,sizeofmark);

      mark[s]=1;

      for(inti=1;i<=n;i++)

           dis[i]=e[s][i];

      dis[s]=0;

 

      intt=n;

      while(t--)

      {

           intmin=Inf;

           intk;

           for(inti=1;i<=n;i++)

                 if(!mark[i]&&dis[i]

                 {

                      min=dis[i];

                      k=i;

                 }

           if(min==Inf)

                 continue;

           mark[k]=1;

           for(inti=1;i<=n;i++)

                 if(!mark[i]&&dis[k]+e[k][i]

                      dis[i]=dis[k]+e[k][i];

      }

#include

#define N1002

#define M20002

struct Edge

{

      intv,next,w;

}edge[M];

int head[N],dis[N],mark[N],cnt[N];

int n,m,s;

 

bool Spfa()

{

      memset(mark,0,sizeofmark);

      memset(cnt,0,sizeofcnt);

      for(inti=0;i<=n;i++) dis[i]=Inf;

      dis[s]=0;mark[s]=1;

      Q<int> q;

      q.push(s);

      while(!q.empty())

      {

           inte=q.front(); q.pop();

           mark[e]=0;

           for(inti=head[e];i!=-1;i=edge[i].next)

           {

                 intv=edge[i].v;

                 if(dis[v]>dis[e]+edge[i].w)

                 {

                      dis[v]=dis[e]+edge[i].w;

 

                      if(!mark[v])

                      {

                            q.push(v);

                            mark[v]=1;

 

                            if(++cnt[v]>=n)

                                  returnfalse;

                      }

                 }

           }

      }

      returntrue;

}

 

int main()

{

      while(scanf("%d%d%d",&n,&m,&s)!=EOF)

      {

           memset(head,-1,sizeofhead);

           for(inti=1;i<=m;i++)

           {

                 intu,v,w;

                 scanf("%d%d%d",&u,&v,&w);

                 edge[i].v=v;

                 edge[i].w=w;

                 edge[i].next=head[u];

                 head[u]=i;

           }

           Spfa();

      }

      return0;

}

 


你可能感兴趣的:(图论—最短路)