zoukankan      html  css  js  c++  java
  • POJ 2387

    题意

    有T条路, n个节点, 求从1->n的最短路

    思路

    模版题, dijkstra算法 ( 数据量大, 无负边 )
    特别注意输入的时候要对重边进行处理

    最短路径问题—Dijkstra算法详解

    AC代码

    #include <iostream>
    #include <algorithm>
    #include <cstdio>
    #include <cstring>
    
    using namespace std;
    const int INF = 0x3f3f3f3f;
    const int maxn = 1e3+10;
    int cost[maxn][maxn];
    bool vis[maxn];
    int d[maxn];
    int n;
    
    void init(){
        memset(d, INF, sizeof(d));
        memset(vis, false, sizeof(vis) );
        for( int i = 1; i <= n; i++ )
            for( int j = 1; j <= n; j++ ){
                if( i == j )  cost[i][j] = 0;
                else    cost[i][j] = INF;
            }
    }
    
    void dijkstra(){
        d[1] = 0;
        for(;;){
            int v = -1;
            for( int i = 1; i <= n; i++ )
                if( !vis[i] && (v == -1 || d[i] < d[v]) )
                    v = i;
            if( v == -1 ) break;
            vis[v] = true;
            for( int i = 1; i <= n; i++ )
                d[i] = min(d[i], d[v] + cost[v][i]);
        }
    }
    
    int main()
    {
        int T;
        int a, b, c;
        while( ~scanf("%d%d",&T, &n) ){
            init();
            while( T-- ){
                scanf("%d%d%d",&a, &b, &c);
                if( c < cost[a][b] && c < cost[b][a] ){ //重边
                    cost[a][b] = c;
                    cost[b][a] = c;
                }
            }
            dijkstra();
            printf("%d
    ",d[n]);
        }
        return 0;
    }
    
  • 相关阅读:
    java的概述 常量 变量
    css 基础2
    css 盒子模型1
    css 基础1
    HTML 基础 3
    HTML基础2
    servletContext百科
    hibernate 一对多双向关联 详解
    hibernate generator class="" id详解
    Hibernate缓存原理与策略
  • 原文地址:https://www.cnblogs.com/JinxiSui/p/9740573.html
Copyright © 2011-2022 走看看