sicily 1003 Go To School

Description

Lucy lives in city GZ. There are N (2 <= N && N <= 100) towns in GZ。There are M (1 <= M <= 1000) two-way roads connecting the towns, and every road has a length w (1 <= w <= 1000). Lucy’s home is in town 1, and the school is in town N. Every day, Lucy goes to school on time, she always takes the shortest path. Please write a program to calculate the length of the shortest path from town 1 to town N.

Input

The input contains several test cases.

The first line contains two integers N, M. The following M lines each contains three integers x, y, w, meaning there is a two-way road between town x and y, and the length of the road is w.

The input will be terminated by EOF.

Output

Output the length of the shortest path from town 1 to town N. It is guaranteed that there is at least one path from town 1 to town N.

Sample Input
 Copy sample input to clipboard
2 12 1 4793 31 3 101 2 42 3 4
Sample Output
4798


这题比较传统,找最短路径,所以知道求最短路径算法的话,这题还是不难的。我用的是dijkstra算法。

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


int edge[110][110];
int const my_MAX = 9999;
int dijkstra(int s, int d)
{
    int dis[110];
    bool vis[110];
    int v, i;


    memset(dis, my_MAX, sizeof(dis));
    dis[0] = 0;
    dis[s] = 0;
    memset(vis, false, sizeof(vis));
    
    while (true) {
        int min = my_MAX;
        for (i = 1; i <= d; i++) {
            if (!vis[i] && dis[i] < min) {
                v = i;
                min = dis[i];
            }
        }               
        if (min == my_MAX)
            break;          
        vis[v] = true;  
        dis[v] = min;
        for (i = 1; i <= d; i++) {
            if (!vis[i] && dis[i] > edge[v][i] + dis[v])
                dis[i] = edge[v][i] + dis[v];
        }
    }
    return dis[d];
}
int main()
{   
//  freopen("input.txt","r",stdin);
    int n, m;
    while (cin >> n >> m) {
        int x, y, d;
        memset(edge, my_MAX, sizeof(edge));
        for (int i = 0; i < m; i++) {
            cin >> x >> y >> d;         
            edge[x][y] = d;
            edge[y][x] = d;
        }
        cout << dijkstra(1,n) << endl;
    }
    return 0;
}                 

                

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值