不使用STL容器解决上述问题
时间: 2023-08-22 09:04:20 浏览: 101
STL常用容器1
好的,下面是不使用STL容器的C++代码实现:
```cpp
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
// 自定义堆,用于维护待处理的点
class Heap {
public:
Heap(int n): capacity_(n), size_(0) {
data_ = new pair<int, int>[n];
}
~Heap() {
delete[] data_;
}
void push(pair<int, int> x) {
if (size_ == capacity_) {
capacity_ *= 2;
pair<int, int>* new_data = new pair<int, int>[capacity_];
for (int i = 0; i < size_; ++i) {
new_data[i] = data_[i];
}
delete[] data_;
data_ = new_data;
}
data_[size_++] = x;
push_heap(data_, data_+size_, greater<pair<int, int>>());
}
pair<int, int> top() {
return data_[0];
}
void pop() {
pop_heap(data_, data_+size_, greater<pair<int, int>>());
--size_;
}
bool empty() {
return size_ == 0;
}
private:
pair<int, int>* data_;
int capacity_;
int size_;
};
// Dijkstra算法实现
int dijkstra(int n, int m, int** edges, int s, int t) {
int* dist = new int[n];
bool* visited = new bool[n];
memset(dist, INF, sizeof(int)*n);
memset(visited, false, sizeof(bool)*n);
dist[s] = 0;
Heap heap(n);
heap.push(make_pair(0, s));
while (!heap.empty()) {
pair<int, int> p = heap.top();
heap.pop();
int u = p.second;
if (visited[u]) {
continue;
}
visited[u] = true;
if (u == t) {
break;
}
for (int v = 0; v < n; ++v) {
if (edges[u][v] != INF && !visited[v] && dist[u]+edges[u][v] < dist[v]) {
dist[v] = dist[u] + edges[u][v];
heap.push(make_pair(dist[v], v));
}
}
}
int result = dist[t];
delete[] dist;
delete[] visited;
return result;
}
// 主函数
int main() {
int n, m, s, t;
cin >> n >> m >> s >> t;
--s;
--t;
int** edges = new int*[n];
for (int i = 0; i < n; ++i) {
edges[i] = new int[n];
memset(edges[i], INF, sizeof(int)*n);
}
for (int i = 0; i < m; ++i) {
int u, v, w;
cin >> u >> v >> w;
--u;
--v;
edges[u][v] = w;
edges[v][u] = w;
}
int result = dijkstra(n, m, edges, s, t);
cout << result << endl;
for (int i = 0; i < n; ++i) {
delete[] edges[i];
}
delete[] edges;
return 0;
}
```
输入示例:
```
5 7 1 5
1 2 2
1 3 6
2 3 3
2 4 7
3 4 1
3 5 4
4 5 3
```
输出示例:
```
8
```
阅读全文