hdu 2544 最短路

http://acm.hdu.edu.cn/showproblem.php?pid=2544

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<queue>
using namespace std;
const int N =105;
const int INF = 0x3f3f3f3f;
int map[N][N],dis[N];
bool vis[N];
int n,m;
void init()
{
    int i , j;
    memset(map,INF,sizeof(map));
    for(i = 1; i <=n ;i ++)
    for(j = 1; j <=m ;j ++)
    if(i == j)map[i][j]=0;
}
void input()
{
    int vi,vj,cost;
    while(m --)
    {
        scanf("%d%d%d",&vi,&vj,&cost);
        if(map[vi][vj]>cost)map[vi][vj]=map[vj][vi]=cost;
    }
}
/*void dijk()//1
{
    int i,j,next,min;
    memset(vis,false,sizeof(vis));
    memset(dis,INF,sizeof(dis));
    dis[1]=0;
    for( i = 1 ;i <=n; i++)
    {
        min = INF;
        for( j = 1 ; j <=n ; j++)
        if(!vis[j] && dis[j] <=min)
        min= dis[next = j];
        vis[next] = true;
        if( min  == INF)break;
        for( j = 1; j<=n ; j++)
            if(!vis[j] && dis[j] >dis[next]+ map[next][j])
            dis[j] = dis[next] +map[next][j];
    }
}*/
/*void dijk()//2
{
    int i,j,next,min;
    memset(vis,false,sizeof(vis));
    for( i = 1; i <= n; i++) dis[i]=map[1][i];
    vis[1]= true;
    for( i = 1 ;i <=n; i++)
    {
        min = INF;
        for( j = 1 ; j <=n ; j++)
        if(!vis[j] && dis[j] <=min)
        min= dis[next = j];
        vis[next] = true;
        if( min  == INF)break;
        for( j = 1; j<=n ; j++)
            if(!vis[j] && dis[j] >dis[next]+ map[next][j])
            dis[j] = dis[next] +map[next][j];
    }
}*/
/*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(map[i][j] > map[i][k]+map[k][j])
    map[i][j] = map[i][k]+map[k][j];
}*/
void spfa()
{
    int i, now;
    memset(vis,false ,sizeof(vis));
    memset(dis,INF,sizeof(dis));
    dis[1]=0;
    queue<int>q;
    q.push(1);
    vis[1]=true;
    while(!q.empty())
    {
        now = q.front();
        q.pop();
        vis[now] = false;
        for( i = 1; i <= n ;i++)
        {
            if(dis[i] > dis[now] +map[now][i])
            {
                dis[i]=map[now][i]+dis[now];
                if(vis[i] == 0)
                {
                    q.push(i);
                    vis[i]=true;

                }

            }
        }
    }
}
int main()
{
    while(scanf("%d%d", &n,&m)!=EOF)
    {
        if( !n || !m)break;
        init();
        input();
        //dijk();
        //floyd();
        printf("%d\n",map[1][n]);
       //printf("%d\n",dis[n]);

    }
}
View Code

初学,bellman-ford 和 spfa 不太懂

posted on 2013-07-30 11:02  blieveboy  阅读(98)  评论(0编辑  收藏  举报

导航