Graph Theory - Take Express

Taurus courier arrived, he could not wait to go to take the courier, but the weather is too hot, so that the beef did not want to take one more step in the hot sun. He got you, you help him plan it, how much he had at least go the distance in order to retrieve the courier.

Enter a description:
Each input comprises a test. 
The first row includes four input positive integer indicating the number of position N (2 <= N <= 10000), a road section the number M (1 <= M <= 100000), the starting position numbers S (1 <= S < = N) and a delivery position number T (1 <= T <= N). Positions numbered from 1 to N, the road is one-way. Data Assurance S ≠ T, can ensure the presence of at least one aspect from the delivery start position reaches the position of the back start position.
Next M rows, each row comprising three positive integer indicating the beginning of the current road number U (1 <= U <= N), the current position of the road to the number of V (1 <= V <= N ) and the current road distance D (1 <= D <= 1000).

Output Description:
For each use case, a single line in the output Arrive delivery starting position back again the shortest distance from the start point.

Input example 1:
3 3 1 3 
1 2 3 
2 3 3 
3 1 1

Output Example 1:
7 
algorithm: spfa
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int N=10010,M=100010;
int h[N],ne[M],e[M],idx,dis[N],w[M];
bool st[N];
int n, m, s, t;
void add(int x, int y, int z){
    e[idx]=y,w[idx]=z,ne[idx]=h[x],h[x]=idx++;
}
int spfa(int x, int y){
    memset(dis,0x3f,sizeof dis);
    dis[x]=0;
    queue<int>q;
    q.push(x);
    st[x]=true;
    while(q.size()){
        auto t=q.front();
        q.pop();
        st[t]=false;
        for(int i=h[t];~i;i=ne[i]){
            int j=e[i];
            if(dis[j]>dis[t]+w[i]){
                dis[j]=dis[t]+w[i];
                if(!st[j]){
                    q.push(j);
                    st[j]=true;
                }
            }
        }
    }
    return dis[y];
}
int main(void){
    memset(h,-1,sizeof h);

    cin>>n>>m>>s>>t;
    for(int i=0,a,b,c;i<m;i++){
        cin>>a>>b>>c;
        add(a,b,c);
    }
    int res=spfa(s,t);
    swap(s,t);
    res+=spfa(s,t);
    cout<<res<<endl;
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/programyang/p/11287984.html