![HDU 3790最短路径问题 [最短路最小花费] HDU 3790最短路径问题 [最短路最小花费]](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
题目链接:【http://acm.hdu.edu.cn/showproblem.php?pid=3790】
最短路径问题
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 25620 Accepted Submission(s): 7650
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
1 2 5 6
2 3 4 5
1 3
0 0
Sample Output
9 11
Source
题解:最短路问题容易解决:最多有1000个顶点,用邻接矩阵保存边,并维护重边,DIJ(O(n^2))可以解决。在维护最短路的同时维护最小费用。如果dis[u]>dis[v]+E[u][v]||(dis[u]==dis[v]+mp[u][v]&&CO[u]>CO[v]+mp[u][v])。
#include<bits/stdc++.h>
using namespace std;
const int INF = 1e7 + ;
const int maxn = ;
int N, M;
int E[maxn][maxn], CO[maxn][maxn];
int dis[maxn], cost[maxn], vis[maxn];
void DIJ(int st, int ed)
{
for(int i = ; i <= N; i++)
dis[i] = cost[i] = INF;
dis[st] = cost[st] = ;
memset(vis, , sizeof(vis));
for(int i = ; i <= N; i++)
{
int x = -, len = INF + ;
for(int j = ; j <= N; j++)
if(!vis[j] && len > dis[j]) len = dis[x = j];
if(x == -) break;
vis[x] = ;
for(int v = ; v <= N; v++)
{
if(dis[v] > dis[x] + E[x][v] || (dis[v] == dis[x] + E[x][v] && cost[v] > cost[x] + CO[x][v]))
{
dis[v] = dis[x] + E[x][v];
cost[v] = cost[x] + CO[x][v];
}
}
}
}
int main ()
{
while(~scanf("%d%d", &N, &M))
{
if(N == && M == ) break;
int u, v, len, co;
for(int i = ; i <= N; i++)
{
for(int j = ; j <= N; j++)
E[i][j] = CO[i][j] = INF;
E[i][i] = CO[i][i] = ;
}
for(int i = ; i <= M; i++)
{
scanf("%d%d%d%d", &u, &v, &len, &co);
if(E[u][v] > len || (E[u][v] == len && CO[u][v] > co))
{
E[u][v] = E[v][u] = len;
CO[u][v] = CO[v][u] = co;
}
}
int st, ed;
scanf("%d%d", &st, &ed);
DIJ(st, ed);
printf("%d %d\n", dis[ed], cost[ed]);
}
return ;
}