最短路徑問題
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 31593 Accepted Submission(s): 9318
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)
Output
輸出 一行有兩個數, 最短距離及其花費。
Sample Input
3 2 1 2 5 6 2 3 4 5 1 3 0 0
Sample Output
9 11
Source
浙大計算機研究所學生複試上機考試-2010年
問題連結:HDU3790 最短路徑問題。
問題描述:參見上文。
問題分析:
這是一個最優化的問題,也是一個單源最短路徑問題,所有要用Dijkstra算法。
程式說明:
圖的表示主要有三種形式,一是鄰接表,二是鄰接矩陣,三是邊清單。鄰接矩陣對于節點多和邊少的情況都不理想。程式中用鄰接表存儲圖,即g[],是一種動态的存儲。數組dist[]中存儲單源(節點s)到各個節點的最短距離。優先隊列q按照邊的權值從小到大排隊,便于計算最短路徑。
與此同時,數組cost[i]中存儲單源(節點s)到各個節點的最花費。需要注意的是,路徑距離相同時,需要選擇花費最小(76行代碼)。
程式中,在Dijkstra算法基礎上增加了72行和76行代碼。
這個問題,由于節點數量比較少,不大于1000,圖還可以用鄰接矩陣表示。那樣的話,代碼則是另外一種寫法。
AC的C++語言程式如下:
/* HDU3790 最短路徑問題 */
#include <iostream>
#include <vector>
#include <queue>
#include <cstdio>
using namespace std;
const int INT_MAX2 = ((unsigned int)(-1) >> 1);
const int MAXN = 10000;
// 邊
struct _edge {
int v, length, cost;
_edge(int v2, int l, int c){v=v2; length=l; cost=c;}
};
// 結點
struct _node {
int u, length;
_node(){}
_node(int u2, int l){u=u2; length=l;}
bool operator<(const _node n) const {
return length > n.length;
}
};
vector<_edge> g[MAXN+1];
int dist[MAXN+1];
int cost[MAXN+1];
bool visited[MAXN+1];
void dijkstra(int start, int n)
{
priority_queue<_node> q;
for(int i=0; i<=n; i++) {
dist[i] = INT_MAX2;
cost[i] = INT_MAX2;
visited[i] = false;
}
dist[start] = 0;
cost[start] = 0;
q.push(_node(start, 0));
_node f;
while(!q.empty()) {
f = q.top();
q.pop();
int u = f.u;
if(!visited[u]) {
visited[u] = true;
int len = g[u].size();
for(int i=0; i<len; i++) {
int v2 = g[u][i].v;
if(visited[v2])
continue;
int templength = g[u][i].length;
int nextdist = dist[u] + templength;
int tempcost = g[u][i].cost;
if(dist[v2] > nextdist) {
dist[v2] = nextdist;
cost[v2] = cost[u] + tempcost; // add code
q.push(_node(v2, dist[v2]));
} else if(dist[v2] == nextdist) {
// 距離相同則取花費少的
cost[v2] = min(cost[v2], cost[u] + tempcost); // add code
}
}
}
}
}
int main()
{
int n, m, src, dest, len, cost2, s, t;
// 輸入資料,建構圖
while(scanf("%d%d",&n,&m) != EOF && (n + m)) {
for(int i=1; i<=m; i++) {
scanf("%d%d%d%d", &src, &dest, &len, &cost2);
g[src].push_back(_edge(dest, len, cost2));
g[dest].push_back(_edge(src, len, cost2));
}
scanf("%d%d", &s, &t);
// Dijkstra算法
dijkstra(s, n);
printf("%d %d\n", dist[t], cost[t]);
// 釋放存儲
for(int i=0; i<=n; i++)
g[i].clear();
}
return 0;
}