1111 Online Map (30 point(s))
程序员文章站
2022-03-13 23:34:08
...
题解
dijkstra模板题。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 510;
vector<int> dispath, Timepath, path;
int pre[MAXN], Time[MAXN], dis[MAXN], e[MAXN][MAXN], w[MAXN][MAXN], weight[MAXN], num[MAXN];
bool visit[MAXN];
int s, d;
void dfs(int u) {
path.push_back(u);
if(u == s) return ;
dfs(pre[u]);
}
int main(){
fill(dis, dis + MAXN, INF);
fill(Time, Time + MAXN, INF);
fill(weight, weight + MAXN, INF);
fill(num, num + MAXN, INF);
fill(e[0], e[0] + MAXN * MAXN, INF);
fill(w[0], w[0] + MAXN * MAXN, INF);
int n, m;
scanf("%d %d", &n, &m);
int a, b, flag, len, t;
for(int i = 0; i < m; i++) {
scanf("%d %d %d %d %d", &a, &b, &flag, &len, &t);
e[a][b] = len;
w[a][b] = t;
if(flag != 1) {
e[b][a] = len;
w[b][a] = t;
}
}
scanf("%d%d", &s, &d);
dis[s] = 0;
weight[s] = 0;
for(int i = 0; i < n; ++i){
int u = -1, minn = INF;
for(int j = 0; j < n; ++j){
if(visit[j] == false && dis[j] < minn){
u = j;
minn = dis[j];
}
}
if(u == -1) break;
visit[u] = true;
for(int v = 0; v < n; ++v){
if(visit[v] == false && e[u][v] != INF){
if(e[u][v] + dis[u] < dis[v]){
dis[v] = dis[u] + e[u][v];
pre[v] = u;
weight[v] = weight[u] + w[u][v];
}else if(e[u][v] + dis[u] == dis[v] && weight[u] + w[u][v] < weight[v]){
weight[v] = weight[u] + w[u][v];
pre[v] = u;
}
}
}
}
dfs(d);
dispath = path; path.clear();
Time[s] = 0;
fill(visit, visit + MAXN, false);
for(int i = 0; i < n; i++) {
int u = -1, minn = INF;
for(int j = 0; j < n; j++) {
if(visit[j] == false && minn > Time[j]) {
u = j;
minn = Time[j];
}
}
if(u == -1) break;
visit[u] = true;
for(int v = 0; v < n; v++) {
if(visit[v] == false && w[u][v] != INF) {
if(w[u][v] + Time[u] < Time[v]) {
Time[v] = w[u][v] + Time[u];
num[v] = num[u] + 1;
pre[v] = u;
} else if(w[u][v] + Time[u] == Time[v] && num[v] > num[u] + 1) {
pre[v] = u;
num[v] = num[u] + 1;
}
}
}
}
dfs(d);
Timepath = path;
printf("Distance = %d", dis[d]);
if(dispath == Timepath) {
printf("; Time = %d: ", Time[d]);
} else {
printf(": ");
for(int i = dispath.size() - 1; i >= 0; i--) printf("%d%s", dispath[i], i == 0 ? "" : " -> ");
printf("\nTime = %d: ", Time[d]);
}
for(int i = Timepath.size() - 1; i >= 0; i--) printf("%d%s", Timepath[i], i == 0 ? "" : " -> ");
return 0;
}
下一篇: 对MySQL数据类型的认识