7.8
前面几天天天都在写搜索写的人都麻了,写几题最短路换换胃口;
Kuangbin:最短路
A. Til the Cows Come Home(POJ_2387)
传送门
一个裸的板子题,直接跑一个dijkstra,就不贴代码了;
B. MPI Maelstrom(POJ_1502)
传送门
从1号点开始发信号,问最少花多少时间可以把信号传遍全图,也就是求1号点单源最短路中的最大值;、
不知道为什么这个题我写了个堆优化的dijkstra一直wa,后来看数据挺小的写了个floyd也wa了,百思不得其解的我把1e2改成100,然后floyd就过了,dijkstra依然wa,我直接???,更加困惑了,这里把两个代码都贴上;
1.Dijkstra堆优化(WA)
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <cmath>
#include <algorithm>
#define ll long long
#define mms(a, b) memset(a, b, sizeof(a))
using namespace std;
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const int maxn = 100 + 5;
int n;
int dis[maxn];
bool vis[maxn];
struct Edge {
int v, w;
};
vector<Edge> G[maxn];
struct Node {
int u, d;
friend bool operator<(const Node& a, const Node& b) {
return a.d > b.d;
}
};
inline void AddEdge(int u, int v, int w) {
G[u].push_back(Edge{ v, w });
}
void Dijkstra() {
for(int i = 1; i <= n; i++) {
dis[i] = inf;
vis[i] = false;
}
dis[1] = 0;
priority_queue<Node> q;
q.push(Node{ 1, 0 });
while (!q.empty()) {
Node tmp = q.top();
q.pop();
int u = tmp.u, d = tmp.d;
if (vis[u])
continue;
else
vis[u] = true;
for (int i = 0; i < G[u].size(); ++i) {
int v = G[u][i].v, w = G[u][i].w;
if (d + w < dis[v]) {
dis[v] = d + w;
q.push(Node{ v, dis[v] });
}
}
}
}
void solve() {
for (int i = 2; i <= n; ++i) {
for (int j = 1; j < i; ++j) {
char tmp[maxn];
scanf("%s", tmp);
if(tmp[0] != 'x') {
AddEdge(i, j, atoi(tmp));
AddEdge(j, i, atoi(tmp));
}
}
}
Dijkstra();
int m = -inf;
for (int i = 1; i <= n; ++i) {
m = max(m, dis[i]);
}
cout << m << '\n';
}
void init() {
mms(dis, inf);
mms(vis, false);
for (int i = 1; i <= n; ++i)
G[i].clear();
}
signed main() {
std::ios::sync_with_stdio(false);
/* cin.tie(nullptr);
cout.tie(nullptr); */
cin >> n;
//init();
solve();
return 0;
}
2.Floyd(AC)
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <cmath>
#include <algorithm>
#define ll long long
#define mms(a, b) memset(a, b, sizeof(a))
using namespace std;
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const int maxn = 100 + 5;
int n;
int G[maxn][maxn];
void floyd() {
for(int k = 1; k <= n; ++k) {
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= n; ++j) {
if(i == k || i == j || j == k)
continue;
if(G[i][k] + G[k][j] < G[i][j])
G[i][j] = G[i][k] + G[k][j];
}
}
}
}
void solve() {
for(int i = 2; i <= n; ++i) {
for(int j = 1; j < i; ++j) {
char str[10];
/* scanf("%s", str); */
cin >> str;
if(str[0] != 'x') {
G[i][j] = atoi(str);
G[j][i] = atoi(str);
}
}
}
G[1][1] = 0;
floyd();
int m = -inf;
for(int i = 1; i <= n; ++i) {
m = max(m, G[1][i]);
}
cout << m << '\n';
}
void init() {
mms(G, inf);
}
int main() {
std::ios::sync_with_stdio(false);
cin >> n;
init();
solve();
}
今天比较摸鱼,最短路有些生了,重新捡了捡,只写了这么俩题;