求一个点到另外一个点的最小距离 #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<algorithm> #include<vector> #include<cstring> #include<cstdio> #include<cmath> #include<cstdlib> #include<sstream> #include<string> #include<map> using namespace std; typedef long long ll; int dx[4] = { 0, 0, 1, -1 }; int dy[4] = { 1, -1, 0, 0 }; #define fo(i,l,r) for (int i = l; i <= r; ++i) #define F 10005 int n, m, s, t,x,y,ww; ll D[F],w[F][F],vis[F]; int main() { cin >> n >> m >> s >> t; fo(i, 1, n) fo(j, 1, n) { if (i != j) w[i][j] = 0x3f3f3f3f3f; } fo(i, 0, n)//注意0的初始化 D[i] = 0x3f3f3f3f3f; D[s] = 0;//从源点到i的距离 fo(i, 1, m) { scanf("%d%d%d", &x, &y, &ww); w[x][y] = ww; w[y][x] = ww; } //dijkstra算法 int k = 0; fo(i, 1, n) { k = 0; fo(j, 1, n) if (!vis[j] && D[j] < D[k])//一开始找源点 k = j; vis[k] = 1; fo(j, 1, n) if (!vis[j]&&D[k] + w[k][j] < D[j]) { D[j] = D[k] + w[k][j]; } } cout << D[t] << endl; return 0; }不用任何容器来实现这个代码
时间: 2024-01-20 17:02:19 浏览: 136
C++ 中pragma once 与 #ifndef _XXX_H_ #define _XXX_H_的区别
5星 · 资源好评率100%
以下是不使用任何容器实现求一个点到另外一个点的最小距离的代码:
```
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<sstream>
#include<string>
#include<map>
using namespace std;
typedef long long ll;
const int F = 10005;
int dx[4] = { 0, 0, 1, -1 };
int dy[4] = { 1, -1, 0, 0 };
int n, m, s, t, x, y, ww;
ll D[F], w[F][F], vis[F];
int main()
{
scanf("%d%d%d%d", &n, &m, &s, &t);
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= n; ++j)
{
if (i != j)
{
w[i][j] = 0x3f3f3f3f3f;
}
}
}
for (int i = 0; i <= n; ++i)
{
D[i] = 0x3f3f3f3f3f;
}
D[s] = 0;
for (int i = 1; i <= m; ++i)
{
scanf("%d%d%d", &x, &y, &ww);
w[x][y] = ww;
w[y][x] = ww;
}
// dijkstra算法
int k = 0;
for (int i = 1; i <= n; ++i)
{
k = 0;
for (int j = 1; j <= n; ++j)
{
if (!vis[j] && D[j] < D[k])
{
k = j;
}
}
vis[k] = 1;
for (int j = 1; j <= n; ++j)
{
if (!vis[j] && D[k] + w[k][j] < D[j])
{
D[j] = D[k] + w[k][j];
}
}
}
printf("%lld\n", D[t]);
return 0;
}
```
这个代码中没有使用任何STL容器,而是使用了基本数据类型和数组来存储和操作数据。
阅读全文