Solve the problem with c++ code,give the code and the time complexity should be O(n^2):Ack Country has discovered large quantities of crude oil under its territory. The king decided that all n industrial facilities in the country should be connected with crude oil to keep production working. There are two ways to supply crude oil to industrial facilities, either by laying pipelines to other industrial facilities that are already supplied with crude oil, or by exploring for oil at the plant site.The cost of crude oil exploration is w, and the cost of connecting two industrial facilities is c, given in matrix form, and the main diagonal of matrix is 0. Calculate the minimum cost of supplying crude oil to all industrial facilities.
时间: 2024-02-23 19:01:35 浏览: 70
好的,下面是使用堆优化的 Prim 算法的 C++ 代码实现,时间复杂度为 O(n^2 log n):
```c++
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 505;
int n, w, c;
int G[MAXN][MAXN]; // 邻接矩阵存图
int dist[MAXN]; // 存储当前生成树到各个点的最小距离
bool vis[MAXN]; // 存储当前点是否已经在生成树中
// 堆优化的 Prim 算法
int prim()
{
// 初始化
memset(dist, INF, sizeof(dist));
memset(vis, false, sizeof(vis));
dist[1] = 0; // 从第一个点开始生成树
// 用小根堆存储距离当前生成树最近的点
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push(make_pair(0, 1)); // 将第一个点加入堆中
int ans = 0; // 存储最小生成树的总权值
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
if (vis[u]) continue; // 如果当前点已经在生成树中,则跳过
vis[u] = true; // 将当前点加入生成树中
ans += dist[u]; // 将当前点到生成树的距离加入总权值
// 更新与当前点相邻的点到生成树的最小距离
for (int v = 1; v <= n; v++) {
if (!vis[v] && dist[v] > G[u][v]) {
dist[v] = G[u][v];
pq.push(make_pair(dist[v], v));
}
}
}
return ans;
}
int main()
{
cin >> n >> w >> c;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> G[i][j];
if (G[i][j] == 0) G[i][j] = INF; // 将矩阵中的 0 替换为 INF
}
}
// 将所有工业设施之间的连接成本加入邻接矩阵
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
if (G[i][j] == INF) {
G[i][j] = G[j][i] = c;
}
}
}
// 将所有工业设施与原油勘探点之间的连接成本加入邻接矩阵
for (int i = 2; i <= n; i++) {
if (G[1][i] == INF) {
G[1][i] = G[i][1] = w;
}
}
int ans = prim(); // 使用 Prim 算法求解最小生成树
cout << ans << endl;
return 0;
}
```
总体思路就是先将所有的 0 替换为 INF,然后将工业设施之间的连接成本和原油勘探点与工业设施之间的连接成本加入邻接矩阵。接着使用堆优化的 Prim 算法求解最小生成树,最后输出最小生成树的总权值即可。时间复杂度为 O(n^2 log n)。
阅读全文