畅通工程续
经典的Floyd和Dijkstra算法的运用
Floyd代码:
#include<iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <functional>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <algorithm>
#define ll long long
#define PI acos(-1)
#define mes(x,y) memset(x,y,sizeof(x))
#define lp pair<ll, ll>
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
ll n, m, i, j, k, t, flag, x, y, z;
const ll INF = 5e9 + 30;
ll mm[205][205];
int main() {
FAST_IO;
while (cin >> n >> m) {
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
mm[i][j] = i == j ? 0 : INF;
}
}
for (i = 0; i < m; i++) {
cin >> x >> y >> z;
mm[x][y] = min(z, mm[x][y]);
mm[y][x] = min(z, mm[y][x]);
}
cin >> x >> y;
for (k = 0; k < n; k++)
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
mm[i][j] = min(mm[i][k] + mm[k][j], mm[i][j]);
cout << (mm[x][y] == INF ? -1 : mm[x][y]) << endl;
}
}
Dijkstra代码:
#include<iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <functional>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <algorithm>
#define ll long long
#define PI acos(-1)
#define mes(x,y) memset(x,y,sizeof(x))
#define lp pair<ll, ll>
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
ll n, m, i, j, k, t, flag, x, y, z;
const ll INF = 5e6 + 30;
string s, s1, s2;
struct node {
ll end = 0, length = 0;
node(ll y, ll z):end(y), length(z) {}
friend bool operator <(node n1, node n2) {
return n1.length > n2.length;
}
};
vector<vector<node>>v;
map<ll, ll>mm;
int main() {
FAST_IO;
while (cin >> n >> m) {
v.clear(); v.resize(n + 1); mm.clear();
priority_queue<node>que;
for (i = 0; i < m; i++) {
cin >> x >> y >> z;
v[x].push_back(node(y, z));
v[y].push_back(node(x, z));
}
cin >> x >> y;
node n1(x, 0);
que.push(n1); bool flag = true;
while (!que.empty()) {
n1 = que.top(); que.pop();
//cout << n1.end<<":" << endl;
if (mm[n1.end])continue;
mm[n1.end] = 1;
if (n1.end == y) {
cout << n1.length << endl;
flag = false;
break;
}
for (i = 0, j = v[n1.end].size(); i < j; i++) {
node n2(v[n1.end][i].end, v[n1.end][i].length + n1.length);
if (mm[n2.end])continue;
que.push(n2);
//cout << n2.end << endl;
}
}
if (flag)cout << -1 << endl;
}
}