dijkastra算法实践poj2387

poj2387题目链接

Dijkstra算法入门

题目描述:找出图G中从点1到N得最短路径

Input

  • Line 1: Two integers: T and N

  • Lines 2..T+1: Each line describes a trail as three space-separated integers. The first two integers are the landmarks between which the trail travels. The third integer is the length of the trail, range 1..100.

Output

  • Line 1: A single integer, the minimum distance that Bessie must travel to get from landmark N to landmark 1.

Sample Input

5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100

Sample Output

90

#include<iostream>
#include<cstring>
using namespace std;

#define inf 999999
#define maxn 1002//最大节点数
int graph[maxn][maxn];//图
int d[maxn];//到每个节点的路径总长度
int T,N;//T为边数,N为节点数
int a,b,c;//a、b为每条边的端点,c为该边权值

void Dijkastra(int graph[1002][1002], int *d, int N){
    int v[1002];//记录已经检查过的节点
    memset(v,0,sizeof(v));
    for(int i=1;i<N+1;i++)  d[i]=(i==1? 0:inf);//第一个节点长度为0
    //遍历所有节点
    for(int i=1;i<N+1;i++){
        int x;
        int m = inf;
        for(int y=1;y<N+1;y++) if(!v[y] && d[y]<=m) m = d[x=y];
        v[x] = 1;//在未标记节点中,找出长度最小的节点并标记
        for(int y=1;y<N+1;y++) d[y] = min(d[y], d[x]+graph[x][y]); 更新各点距离
    } 
}


int main()
{   
    while(cin >> T >> N){
        memset(graph,inf,sizeof(graph));
        for(int i=1;i<T+1;i++){
            cin >> a >> b >> c;
            if(c > graph[a][b]) continue;
            graph[a][b] = c;
            graph[b][a] = c;
        }
        Dijkastra(graph, d, N);
        cout <<d[N]<<endl;
    }
 } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值