牛牛的快递到了,他迫不及待地想去取快递,但是天气太热了,以至于牛牛不想在烈日下多走一步。他找来了你,请你帮他规划一下,他最少要走多少距离才能取回快递。
输入描述:
每个输入包含一个测试用例。
输入的第一行包括四个正整数,表示位置个数N(2<=N<=10000),道路条数M(1<=M<=100000),起点位置编号S(1<=S<=N)和快递位置编号T(1<=T<=N)。位置编号从1到N,道路是单向的。数据保证S≠T,保证至少存在一个方案可以从起点位置出发到达快递位置再返回起点位置。
接下来M行,每行包含三个正整数,表示当前道路的起始位置的编号U(1<=U<=N),当前道路通往的位置的编号V(1<=V<=N)和当前道路的距离D(1<=D<=1000)。
输出描述:
对于每个用例,在单独的一行中输出从起点出发抵达快递位置再返回起点的最短距离。
输入例子1:
3 3 1 3 1 2 3 2 3 3 3 1 1
输出例子1:
7
算法: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; }