6.2-Til the Cows Come Home-dijk

Bessie is out in the field and wants to get back to the barn to get as much sleep as possible before Farmer John wakes her for the morning milking. Bessie needs her beauty sleep, so she wants to get back as quickly as possible.

Farmer John's field has N (2 <= N <= 1000) landmarks in it, uniquely numbered 1..N. Landmark 1 is the barn; the apple tree grove in which Bessie stands all day is landmark N. Cows travel in the field using T (1 <= T <= 2000) bidirectional cow-trails of various lengths between the landmarks. Bessie is not confident of her navigation ability, so she always stays on a trail from its start to its end once she starts it.

Given the trails between the landmarks, determine the minimum distance Bessie must walk to get back to the barn. It is guaranteed that some such route exists.

輸入
* 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.

輸出
* Line 1: A single integer, the minimum distance that Bessie must travel to get from landmark N to landmark 1.
樣例輸入

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

樣例輸出

90

提示
INPUT DETAILS:

There are five landmarks.

OUTPUT DETAILS:

Bessie can get home by following trails 4, 3, 2, and 1.

dijk裸題

#include<iostream>
#include<string>
#include<algorithm>
#define MAX 9999999
using namespace std;
int u,v,dis[1111],vis[1111],ma[1111][1111];// 邊數,點數
void dijk(int s)//如果還需要打印路徑,則還需要定義一個數組用來存放前一個節點的序號
{
    for(int i=1;i<=v;i++)
    {
        dis[i]=ma[s][i];
    }
    for(int i=1;i<=v;i++)
    {
        int k=1;
        int mini=MAX;
        for(int j=1;j<=v;j++)
        {
            if(!vis[j]&&dis[j]<mini)
            {
                mini=dis[j];
                k=j;
            }
        }
        vis[k]=1;
        for(int j=1;j<=v;j++)
        {
            if(dis[k]+ma[k][j]<dis[j])
            {
                dis[j]=dis[k]+ma[k][j];
            }
        }
    }
}
int main()
{
    while(cin>>u>>v)  
    {  
        for(int i = 0 ; i <=v;i++)  
        {  
            for(int j = 0 ; j <=v;j++)  
            {  
                ma[i][j]=MAX;  
            }  
            ma[i][i]=0;  
            vis[i]=0;  
            dis[i]=MAX;  
        }  
        for(int i = 1 ;i<=u;i++)  
        {  
            int a , b , len;  
            cin>>a>>b>>len;  
            if(ma[a][b]>len)  
            {  
                ma[a][b]=ma[b][a]=len;  
            }  
        }  
        dijk(1);  
        printf("%d\n",dis[v]);  
    }  
    return 0 ;  
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章