spfa算法解决POJ 2387

Description

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.

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
 
  
 
  
spfa算法的输入是很讲究的,之所以这样
我想是方便后面用queue来存储和取出。
明白了输入是怎么一回事,搞清spfa的过程
就不是问题了。我在下面的代码给出了我
研究过程的代码,肯定会对大家有帮助的。
View Code
#include "iostream"

#include "queue"

using namespace std;

#define N 10000

#define Max 0x7FFFFFFF

typedef struct Node{

    int u, value, next;

}node;

node e[N];

int n, m;

int dis[N], p[N];

bool vis[N];

void init(){

    memset(p, -1, sizeof(p));

    memset(vis, false, sizeof(vis));

    fill(dis, dis+N, Max);

    int temp = 0; 

    int a, b, c;

    for(int i=0; i<n; i++){

        cin>>a>>b>>c;

        e[temp].u = b;

        e[temp].value = c;

        e[temp].next = p[a];

        p[a] = temp;

        temp ++;

        e[temp].u = a;

        e[temp].value = c;

        e[temp].next = p[b];

        p[b] = temp;

        temp++;

    }

}

void spfa(int s){

    dis[s] = 0;

    queue<int> q;

    q.push(s);

    while(!q.empty()){

        int t = q.front();

        q.pop();

        vis[t] = false;

        int j;

        for(j=p[t]; j!=-1; j=e[j].next){

            int w=e[j].value;

            int temp = e[j].u;

            if(w+dis[t] < dis[temp]){

                dis[temp] = w+dis[t];

                if(!vis[temp]){

                    vis[temp] = true;

                    q.push(temp);

                }

            }

        }

    }

}

int main()

{

    while(cin>>n>>m && (n+m))

    {

        init();

        spfa(1);

        cout<<dis[m]<<endl;

    }

    return 0;

}
 
  

 

 

你可能感兴趣的:(SPFA)