POJ 2378

  一道单源最短路的入门题,用于练习用C++写SPFA的模版,将边用邻接表建好,用SPFA求出最短路即可。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>

using namespace std;

const int MAX_EDGE = 2010 , MAX_VERTEX =  1010 , INF =0x3f3f3f3f;

typedef class node
{
    public:
    int val , vertex;
    class node *next;
    node()
    {
        val = INF;
        vertex = -1;
        next = NULL;
    }
    node( int _vertex , int _val )
    {
        val = _val;
        vertex = _vertex;
        next = NULL;
    }
}Node;

class node * head[ MAX_VERTEX ];

bool inQue[ MAX_VERTEX ];
int dist[ MAX_VERTEX ];
queue< int > que;

void add( int from , int to , int edgeVal )
{
    Node *pre = head[ from ] , *now = head[ from ] , *tmp = new Node( to , edgeVal);
    if( head[ from ] == NULL )
    {
        head[ from ] = tmp;
        return ;
    }
    while( now != NULL )
    {
        pre = now;
        now = now->next;
    }
    pre->next = tmp;
    return ;
}

int spfa( int src , int dst )
{
    while( !que.empty() )
    {
        que.pop();
    }
    for( int i = 0 ; i <= dst ; i++ )
    {
        inQue[ i ] = false;
        dist[ i ] = INF;
    }
    dist[ src ] = 0;
    inQue[ src ] = true;
    que.push( src );
    while( !que.empty() )
    {
        int now = que.front();
        que.pop();
        inQue[ now ] = false;

        for( Node * i = head[ now ] ; i != NULL ; i = i->next )
        {
            int len = i->val , dstVer = i->vertex;
            if( dist[ now ] + len < dist[ dstVer ] )
            {
                dist[ dstVer ] = len + dist[ now ];
                if( inQue[ dstVer ] == false )
                {
                    inQue[ dstVer ] = true;
                    que.push( dstVer );
                }
            }
        }
    }
    return dist[ dst ];
}

int main()
{
    int roadNum , verNum;
    while( scanf("%d%d",&roadNum , &verNum ) != EOF )
    {
        for( int i = 0 ; i < roadNum ; i++ )
        {
            int a,b,value;
            scanf("%d%d%d",&a,&b,&value);
            add( a , b , value );
            add( b , a , value );
        }
        printf("%d\n" , spfa( 1 , verNum ) );
    }
    return 0;
}

 

posted @ 2013-04-14 15:50  等待电子的砹  阅读(195)  评论(0编辑  收藏  举报