Description
给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花费最少的。
Input
输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。最后一行是两个数 s,t;起点s,终点。n和m为0时输入结束。
(1<n<=1000, 0<m<100000, s != t)
(1<n<=1000, 0<m<100000, s != t)
Output
输出 一行有两个数, 最短距离及其花费。
Sample Input
3 2 1 2 5 6 2 3 4 5 1 3 0 0
Sample Output
9 11
求最短路径,如果有多条,求花费最小的那条
ACcode:
#include <iostream>
#include <cstdio>
#include <cstring>
#define maxn 1000
#define inf 0x3f3f3f3f
using namespace std;
bool vis[maxn];
int pre[maxn];
int cost[maxn][maxn],len[maxn][maxn],lowcost[maxn],lowlen[maxn];
void dij(int n,int beg,int ed){
for(int i=1;i<=n;++i){
lowlen[i]=len[beg][i];
lowcost[i]=cost[beg][i];
vis[i]=false;
pre[i]=-1;
}
lowcost[beg]=0;
for(int j=1;j<=n;j++){
int k=-1;
int minn=inf;
for(int i=1;i<=n;i++)
if(!vis[i]&&lowcost[i]<minn){
minn=lowcost[i];
k=i;
}
if(k==-1)break;
vis[k]=true;
for(int i=1;i<=n;i++){
if(!vis[i]&&lowcost[k]+cost[k][i]<lowcost[i]){
lowcost[i]=lowcost[k]+cost[k][i];
lowlen[i]=lowlen[k]+len[k][i];
pre[i]=k;
}
else if(!vis[i]&&lowcost[k]+cost[k][i]==lowcost[i]&&lowlen[k]+len[k][i]<lowlen[i]){
lowlen[i]=lowlen[k]+len[k][i];
}
}
}
}
void add(){
int u,v,mcost,mlen;
scanf("%d%d%d%d",&u,&v,&mcost,&mlen);
if(cost[u][v]>mcost){
cost[u][v]=cost[v][u]=mcost;
len[u][v]=len[v][u]=mlen;
}
}
int main(){
int n,m;
while(~scanf("%d%d",&n,&m)&&n+m){
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
len[i][j]=cost[i][j]=inf;
while(m--)add();
int st,ed;
scanf("%d%d",&st,&ed);
dij(n,st,ed);
// for(int i=1;i<=n;++i)printf("lowcost[%d]=%d lowlen[%d]=%d \n",i,lowcost[i],i,lowlen[i]);
cout<<lowcost[ed]<<" "<<lowlen[ed]<<'\12';
}
return 0;
}
/*
3 2
1 2 5 6
2 3 4 5
1 3
4 4
1 3 5 6
3 4 4 5
1 2 5 2
2 4 4 3
1 4
4 4
1 3 5 2
3 4 4 3
1 2 5 6
2 4 4 5
1 4
0 0
*/