hdu 2544 (Dijkstra/SPFA模板)

 

/*
此题纯属套模板
调用时,初始结点s,目标结点e,则

SPFA(s);

cout<<d[e]<<endl;

即可。注意结点是从1存储到N。

不能连通时值为MAX*/

#include <stdio.h>

#include <string.h>



int d[1002],n,m;

int edges[1005][1005];

int queue[1000001];

#define MAX 999999999

#define N 1001

/*

int SPFA(int s)

{

    int i;

    bool visit[N] = {false};

    int front = 0, rear = 1; 

    memset(queue,0,sizeof(queue));

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

        d[i] = MAX;

    //int path[N];

    queue[front] = s;

    visit[s] = true;

    d[s] = 0;

    while(front<rear)

    {

        int u = queue[front];

        visit[u] = false;

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

        {

            if (d[i]>d[u]+ edges[u][i])

            {

                d[i]= d[u]+edges[u][i];

                //path[i] = u;

                if( !visit[i] )

                {

                    visit[i] = true;

                    queue[rear++] = i;

                }

            }

        }

        front++;

    }

    return 0;

}

*/

void dijkstra(int v)

{

        int i,j;

        bool s[N]={false};

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

                d[i]=edges[v][i];

        d[v]=0;s[v]=true;

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

        {

                int temp=MAX;

                int u=v;

                for(j=1;j<=n;j++)

                        if((!s[j])&&(d[j]<temp))

                        {

                                u=j;

                                temp=d[j];

                        }

                        s[u]=true;

                        for(j=1;j<=n;j++)

                                if((!s[j])&&(edges[u][j]<MAX)&&(d[u]+edges[u][j])<d[j])

                                        d[j]=d[u]+edges[u][j];

        }

  

}



int main()

{

    int i,j,a,b,c;

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

    {

        for(i=0;i<=1000;i++){

            for(j=0;j<=i;j++)

            {

                edges[i][j]=MAX;

                edges[j][i]=MAX;

            }

        }

        for(i=0;i<m;i++)

        {

            scanf("%d %d %d",&a,&b,&c);

            if(edges[a][b]>c){

                edges[a][b]=c;

                edges[b][a]=c;

            }

        }

        

      //  SPFA(1);

		dijkstra(1);

        printf("%d\n",d[n]);

    }

    return 0;

}

你可能感兴趣的:(dijkstra)