#include<iostream> #include<algorithm> #include<cstring> #define N 25005 using namespace std; typedef long long ll; ll road[2501][2501]; int main() { int n, m, s, t; bool visit[2501]; ll best[2501] = { 0 }; for (int i = 0; i <= 2500; i++) for (int j = 0; j <= 2500; j++) road[i][j] = 1e18; for (int i = 0; i <= 2500; i++) best[i] = 1e18; cin >> n >> m >> s >> t; best[s] = 0; while (m--) { int a, b; ll c; cin >> a >> b >> c; if (c<road[a][b]) road[a][b] = road[b][a] = c; } while (1) { int ma = 1e18, target = -1; for (int i = 1; i <= n; i++) { if (!visit[i] && ma>best[i]) { ma = best[i]; target = i; } } if (target == -1)break; visit[target] = 1; for (int i = 1; i <= n; i++) { if (!visit[i]) { best[i] = min(best[i], best[target] + road[target][i]); } } } cout << best[t];//output return 0; }对这个代码进行降重
时间: 2024-01-20 12:02:45 浏览: 130
这是一个单源最短路径算法的实现,采用了 Dijkstra 算法。降重的方法有很多,这里提供一种基本的思路:
1. 删除无用的注释和空格。
2. 将变量名进行简化。
3. 将常量进行宏定义。
4. 统一缩进。
5. 将一些重复的操作进行函数封装。
根据上述思路,可以得到以下降重后的代码:
```c++
#include<iostream>
#include<algorithm>
#include<cstring>
#define N 25005
#define INF 1e18
typedef long long ll;
using namespace std;
ll road[N][N];
bool visit[N];
ll best[N];
void init() {
for (int i = 0; i <= N; i++) {
for (int j = 0; j <= N; j++) {
road[i][j] = INF;
}
best[i] = INF;
}
}
void dijkstra(int n, int m, int s, int t) {
best[s] = 0;
while (true) {
int ma = INF, target = -1;
for (int i = 1; i <= n; i++) {
if (!visit[i] && ma > best[i]) {
ma = best[i];
target = i;
}
}
if (target == -1) break;
visit[target] = true;
for (int i = 1; i <= n; i++) {
if (!visit[i]) {
best[i] = min(best[i], best[target] + road[target][i]);
}
}
}
cout << best[t] << endl;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
init();
int n, m, s, t;
cin >> n >> m >> s >> t;
while (m--) {
int a, b;
ll c;
cin >> a >> b >> c;
if (c < road[a][b]) {
road[a][b] = road[b][a] = c;
}
}
dijkstra(n, m, s, t);
return 0;
}
```
阅读全文