hduoj2544:最短路

来源:互联网 发布:知乎数据挖掘考研 编辑:程序博客网 时间:2024/06/05 00:12

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2544

权值为正的单源最短路径问题,用dijkstra+priority_queue优化,当然也可以直接使用dijkstra。

#include <iostream>#include <stdio.h>#include <string.h>#include <queue>using namespace std;#define INF 1000000const int maxn = 105 ;int map[maxn][maxn] ;int dist[maxn] ;bool vis[maxn] ;int n ;int m ;struct Node{int x ;int y ;};bool operator<(Node a , Node b){return a.x > b.x ;}void dijkstra(int s) ;void init() ;int main(){int i ;int p ;int q ;int k ;    //freopen("data.in" , "r" , stdin) ;while(scanf("%d%d" , &n , &m)!=EOF && m && n){init() ;for(i = 1 ; i <= m ; i ++){scanf("%d%d%d" , &p , &q , &k) ;if(map[p][q] > k){map[p][q] = map[q][p] = k ;}}//scanf("%d%d" , &p , &q) ;dijkstra(1) ;printf("%d\n" , dist[n]) ;}    return 0;}void init(){int i ;int j ;for(i = 0 ; i < maxn ; i ++){dist[i] = INF ;vis[i] = 0 ;for(j = 0 ; j < maxn ; j ++)map[i][j] = INF ;}}void dijkstra(int s){int i ;priority_queue<Node> Q ;Node a ;Node b ;a.x = 0 ;a.y = s ;dist[s] = 0 ;Q.push(a) ;while(!Q.empty()){a = Q.top() ;Q.pop() ;if(vis[a.y])continue ;vis[a.y] = 1 ;for(i = 1 ; i <= n ; i ++){if(!vis[i] && map[a.y][i] < INF && dist[i] > a.x + map[a.y][i] ){dist[i] = a.x + map[a.y][i] ;b.x = dist[i] ;b.y = i ;Q.push(b) ;}}}}


原创粉丝点击