天天看點

HDU 2544 最短路 dijkstra floyd

純屬複習資料結構

/*
        stratege :  floyd
        Status : 2012-05-14 23:34:01   Accepted	1002	31 MS	268 KB	Visual C++	johnsondu
*/

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std ;

const int MAXN = 105 ;
const int INF = 0xfffffff ;
int mat[MAXN][MAXN] ;
int n, m ;

void init ()
{
    int i, j ;
    int a, b, w ;
    for (i = 1; i <= n; i ++)
        for (j = 1; j <= n; j ++)
            mat[i][j] = INF ;
    for (i = 0; i < m; i ++)
    {
        scanf ("%d%d%d", &a, &b, &w) ;
        if (mat[a][b] > w)
            mat[a][b] = mat[b][a] = w ;
    }
}

void floyd ()
{
    int i, j, k ;
    for (k = 1; k <= n; k ++)
        for (i = 1; i <= n; i ++)
            for (j = 1; j <= n; j ++)
            {
                if (mat[i][k] + mat[k][j] < mat[i][j])
                    mat[i][j] = mat[i][k] + mat[k][j] ;
            }
}

int main ()
{
    while (scanf ("%d%d", &n, &m), n | m)
    {
        init () ;
        floyd () ;
        printf ("%d\n", mat[1][n]) ;
    }
}


/*
        stratege :  dijkstra 
        Status : 2012-05-14 23:24:42	Accepted	1002	15 MS	268 KB	Visual C++	johnsondu
*/
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std ;

const int MAXN = 105 ;
const int INF = 0xfffffff ;
int mat[MAXN][MAXN] ;
bool visit[MAXN] ;
int dist[MAXN] ;
int n, m ;

void init ()
{
    int i, j ;
    int a, b, w ;
    for (i = 1; i <= n; i ++)
        for (j = 1; j <= n; j ++)
            mat[i][j] = INF ;
    for (i = 0; i < m; i ++)
    {
        scanf ("%d%d%d", &a, &b, &w) ;
        if (mat[a][b] > w)
            mat[a][b] = mat[b][a] = w ;
    }
    memset (visit, false, sizeof(visit)) ;
}

void dijkstra()
{
    int i, j ;
    for (i = 2; i <= n; i ++)
        dist[i] = mat[1][i] ;

    dist[1] = INF ;
    visit[1] = true ;

    for (i = 2; i <= n; i ++)
    {
        int min = INF, mTag ;
        for (j = 1; j <= n; j ++)
            if (!visit[j] && min > dist[j])
            {
                min = dist[j] ;
                mTag = j ;
            }
        visit[mTag] = true ;
        for (j = 1; j <= n; j ++)
            if (!visit[j] && dist[mTag] + mat[mTag][j] < dist[j])
                dist[j] = dist[mTag] + mat[mTag][j] ;
    }
}

int main ()
{
    while (scanf ("%d%d", &n, &m), n | m)
    {
        init () ;
        dijkstra () ;
        printf ("%d\n", dist[n]) ;
    }
}