最短路径问题Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 37767 Accepted Submission(s): 11030 Problem 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时输入结束。 Output 输出 一行有两个数, 最短距离及其花费。 Sample Input 3 2 1 2 5 6 2 3 4 5 1 3 0 0 Sample Output 9 11 Source Recommend notonlysuccess | We have carefully selected several similar problems for you: 2544 2066 1217 1142 1548 |
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
#include<iostream>
using namespace std;
typedef long long ll;
int n,m;
ll cost[10000],len[10000];
int v[10000];
ll G1[1005][1005],G2[1005][1005];
ll MAX=1e9+5;
void DJ(int k){
memset(v,0,sizeof(v));
for(int i=1;i<=n;i++)
cost[i]=len[i]=MAX;
cost[k]=len[k]=0;
v[k]=1;
queue<int>qq;
qq.push(k);
while(!qq.empty()){
// printf("YES\n");
int g=qq.front();
//printf("g === %d\n",g);
qq.pop();
v[g]=0;
for(int i=1;i<=n;i++){
if(len[i]>len[g]+G1[g][i]){
len[i]=len[g]+G1[g][i];
cost[i]=cost[g]+G2[g][i];
if(!v[i]){
v[i]=1;
qq.push(i);
}
}
else if(len[i]==len[g]+G1[g][i]){
if(cost[i]>cost[g]+G2[g][i])
cost[i]=cost[g]+G2[g][i];
}
}
}
return ;
}
int main(){
while(scanf("%d%d",&n,&m)!=EOF){
if(n==0||m==0)
return 0;
for(int i=0;i<=n;i++)
for(int j=0;j<=n;j++){
if(i!=j)
G1[i][j]=G2[i][j]=MAX;
else
G1[i][j]=G2[i][j]=0;
}
while(m--){
int a,b;
ll d,p;
scanf("%d %d %lld %lld",&a,&b,&d,&p);
if(G1[a][b]>d){
G1[a][b]=G1[b][a]=d;
G2[a][b]=G2[b][a]=p;
}
else if(G1[a][b]==p)
G2[a][b]=G2[b][a]=min(G2[a][b],p);
}
int s,e;
scanf("%d %d",&s,&e);
DJ(s);
printf("%lld %lld\n",len[e],cost[e]);
}
return 0;
}