最短路程 最短时间问题。。
直接莽了两遍Dijstra...后面再看看小伙伴们有没有更好的方法。
#include <iostream>
#include <vector>
#include <climits>
#define MAX 510
using namespace std;
int n, k;
struct Node {
int v;
int time;
int len;
};
vector <Node> m[MAX];
int disLen[MAX];
int preLen[MAX];
int timeLen[MAX];
int interTime[MAX];
int preTime[MAX];
int timeTime[MAX];
bool isVis[MAX];
void InitLen() {//初始化参数
for (int i = 0; i < MAX; i++) {
disLen[i] = INT_MAX;
preLen[i] = i;
timeLen[i] = INT_MAX;
isVis[i] = false;
}
}
void InitTime() {//初始化参数
for (int i = 0; i < MAX; i++) {
interTime[i] = INT_MAX;
preTime[i] = i;
timeTime[i] = INT_MAX;
isVis[i] = false;
}
}
void DijstraLen(int st) {
disLen[st] = 0;
timeLen[st] = 0;
for (int i = 0; i < n; i++) {
int min = INT_MAX, u = -1;
for (int j = 0; j < n; j++) {
if (!isVis[j] && min > disLen[j]) {
min = disLen[j];
u = j;
}
}
if (u == -1) break;
isVis[u] = true;
for (int j = 0; j < m[u].size(); j++) {
int v = m[u][j].v;
if (!isVis[v]) {
if (disLen[u] + m[u][j].len < disLen[v]) {
disLen[v] = disLen[u] + m[u][j].len;
timeLen[v] = timeLen[u] + m[u][j].time;
preLen[v] = u;
}
else if (disLen[u] + m[u][j].len == disLen[v] && timeLen[u] + m[u][j].time < timeLen[v]) {
preLen[v] = u;
timeLen[v] = timeLen[u] + m[u][j].time;
}
}
}
}
}
void DijstraTime(int st) {
interTime[st] = 0;
timeTime[st] = 0;
for (int i = 0; i < n; i++) {
int min = INT_MAX, u = -1;
for (int j = 0; j < n; j++) {
if (!isVis[j] && min > timeTime[j]) {
min = timeTime[j];
u = j;
}
}
if (u == -1) break;
isVis[u] = true;
for (int j = 0; j < m[u].size(); j++) {
int v = m[u][j].v;
if (!isVis[v]) {
if (timeTime[v] > timeTime[u] + m[u][j].time) {
timeTime[v] = timeTime[u] + m[u][j].time;
interTime[v] = 1 + interTime[u];
preTime[v] = u;
}
else if (timeTime[v] == timeTime[u] + m[u][j].time && interTime[v] > 1 + interTime[u]) {
interTime[v] = 1 + interTime[u];
preTime[v] = u;
}
}
}
}
}
int main() {
cin >> n >> k;
int u, v, tag;
Node tempNode;
for (int i = 0; i < k; i++) {
cin >> u >> v >> tag >> tempNode.len >> tempNode.time;
tempNode.v = v;
m[u].push_back(tempNode);
if (tag != 1) {//双行道
tempNode.v = u;
m[v].push_back(tempNode);
}
}
cin >> u >> v;
InitLen();
DijstraLen(u);
vector <int> ansLen;
int prel = v;
while (prel != u) {
ansLen.push_back(prel);
prel = preLen[prel];
}
InitTime();
DijstraTime(u);
vector <int> ansTime;
int pret = v;
while (pret != u) {
ansTime.push_back(pret);
pret = preTime[pret];
}
if (ansTime != ansLen) {//线路不相同
cout << "Distance = " << disLen[v] << ": " << u;
for (int i = ansLen.size() - 1; i >= 0; i--) {
cout << " -> " << ansLen[i];
}
cout << endl;
}
else {//线路相同
cout << "Distance = " << disLen[v] << "; ";
}
cout << "Time = " << timeTime[v] << ": " << u;
for (int i = ansTime.size() - 1; i >= 0; i--) {
cout << " -> " << ansTime[i];
}
cout << endl;
return 0;
}