dijkastra算法实践poj2387

来源:互联网 发布:linux sort 0 编辑:程序博客网 时间:2024/06/06 01:31

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;    } } 
原创粉丝点击