最短路径问题
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 27849 Accepted Submission(s): 8284
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时输入结束。
(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
#include<cstdio>
#include<cstring>
const int inf = 0x3f3f3f3f;
const int N = 1010;
int n, m;
int e[N][N], e1[N][N], dis[N], dis1[N], book[N];
void Dijkstra(int st,int ed){
memset(book, 0, sizeof(book));
for(int i = 1; i <= n; i++){
dis[i] = e[st][i];
dis1[i] = e1[st][i];
}
int u;
for(int i = 1; i <= n-1; i++){
int minn = inf, minn1 = inf;
for(int j = 1; j <= n; j++){
if(book[j] == 0 && (minn > dis[j]||minn == dis[j] && minn1>dis1[j])){
minn = dis[j];
minn1 = dis1[j];
u = j;
}
}
book[u] = 1;
for(int j = 1; j <= n; j++){
if((dis[j] > dis[u] + e[u][j])||((dis[j] == dis[u] + e[u][j]) && (dis1[j] > dis1[u] + e1[u][j]))){
dis[j] = dis[u] + e[u][j];
dis1[j] = dis1[u] + e1[u][j];
}
}
}
printf("%d %d\n", dis[ed],dis1[ed]);
}
int main(){
while(scanf("%d%d", &n, &m)!=EOF && (n!=0||m!=0)){
memset(e, inf, sizeof(e));
memset(e1, inf, sizeof(e1));
while(m--){
int a, b, d, p;
scanf("%d%d%d%d",&a, &b, &d, &p);
if(d<e[a][b] || (e[a][b] == d && e1[a][b] > p)){
e[a][b] = e[b][a] = d;
e1[a][b] = e1[b][a] = p;
}
}
int start, end;
scanf("%d%d", &start, &end);
Dijkstra(start, end);
}
return 0;
}