力扣双周赛--最小生成树的应用

https://leetcode-cn.com/contest/biweekly-contest-7/problems/optimize-water-distribution-in-a-village/

这个题目可以转化为最小生成树。构建虚拟结点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;
    }
};

 

 


版权声明:本文为XueWang1原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。