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

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

力扣双周赛--最小生成树的应用_第1张图片

这个题目可以转化为最小生成树。构建虚拟结点0,并且将所有结点与之联系,长度为wi,如下:

力扣双周赛--最小生成树的应用_第2张图片

然后对改图求最小生成树,即可求得最小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& father,int i){
        int a=i;
        while(father[i]!=i){
            i=father[i];
        }
        father[a]=i;
        return i;
    }
    int minCostToSupplyWater(int n, vector& wells, vector>& pipes) {
        vector edges;
        for(int i=1;i<=n;i++){
            Edge e(0,i,wells[i-1]);
            edges.push_back(e);
        }
        for(int i=0;i father(n+1);
        for(int i=0;i<=n;i++)
            father[i]=i;
        int ans=0;
        for(int i=0;i

 

 

你可能感兴趣的:(C++,leetcode,最小生成树)