【leetcode 1584】連線所有點的最小費用
阿新 • • 發佈:2021-10-11
https://leetcode-cn.com/problems/min-cost-to-connect-all-points/
分析
模板題。
#define P pair<int, int> #define PI pair<int, P> class Solution { public: vector<PI> V; int fa[1010]={0}; int find(int n) { return fa[n]==n?n:fa[n]=find(fa[n]); } int minCostConnectPoints(vector<vector<int>>& points) { int m=points.size(); for(int i=0;i<m;i++)fa[i]=i; for(int i=0;i<m;i++) { int x1=points[i][0],y1=points[i][1]; for(int j=i+1;j<m;j++) { int x2=points[j][0],y2=points[j][1]; V.push_back(PI(abs(x1-x2)+abs(y1-y2),P(i,j))); } } sort(V.begin(),V.end()); int ans=0; for(auto x:V) { int dist=x.first,node1=x.second.first,node2=x.second.second; if(find(node1)!=find(node2)) { ans+=dist; fa[find(node1)]=find(node2); } } return ans; } };