这个题目可以转化为最小生成树。构建虚拟结点0,并且将所有结点与之联系,长度为wi,如下:
然后对改图求最小生成树,即可求得最小cost。
struct Edge{
int n1,n2;
int cost;
Edge(int n1,int n2,int cost){
this->n1=n1;
this->n2=n2;
this->cost=cost;
}
};
bool cmp(Edge e1,Edge e2){
return e1.cost<e2.cost;
}
class Solution {
public:
int findFather(vector<int>& father,int i){
int a=i;
while(father[i]!=i){
i=father[i];
}
father[a]=i;
return i;
}
int minCostToSupplyWater(int n, vector<int>& wells, vector<vector<int>>& pipes) {
vector<Edge> edges;
for(int i=1;i<=n;i++){
Edge e(0,i,wells[i-1]);
edges.push_back(e);
}
for(int i=0;i<pipes.size();i++){
Edge e(pipes[i][0],pipes[i][1],pipes[i][2]);
edges.push_back(e);
}
sort(edges.begin(),edges.end(),cmp);
vector<int> father(n+1);
for(int i=0;i<=n;i++)
father[i]=i;
int ans=0;
for(int i=0;i<edges.size();i++){
int f1=findFather(father,edges[i].n1);
int f2=findFather(father,edges[i].n2);
if(f1!=f2){
father[f1]=f2;
ans+=edges[i].cost;
}
}
return ans;
}
};