class Solution {
private:
struct Edge
{
int u, v, cost;
bool operator<(const Edge& in)const
{
return cost < in.cost;
}
};
vector<Edge>edges;
vector<int>parent;
public:
int minCostConnectPoints(vector<vector<int>>& points) {
int size = points.size();
if (size == 0)return 0;
parent = vector<int>(size+1, 0);
for (int i = 0; i <=size; i++)
parent[i] = i;
int ans = 0;
for (int i = 0; i < points.size() - 1; i++)
for (int j = i + 1; j < points.size(); j++)
{
edges.push_back({i,j,(abs(points[i][0]-points[j][0])+abs(points[i][1]-points[j][1]))});
}
//计算每两个点之间的距离
sort(edges.begin(), edges.end());
for (auto& t : edges)
{
int tx = find(t.u);
int ty = find(t.v);
if (tx != ty)
{//这是为了防止生成圈
ans += t.cost;
merge(tx,ty);
}
}
return ans;
}
int find(int in)
{
return in == parent[in] ? in : parent[in] = find(parent[in]);
}
void merge(int x, int y)
{
int X = find(x);
int Y = find(y);
if (X == Y)return;
parent[X] = parent[Y];
}
};
leetcode连接所有点的最小费用与Krustal算法模板
最新推荐文章于 2023-08-21 14:05:52 发布