Leetcode 1584. 连接所有点的最小费用 最小生成树 prime/kruskal C++tuple的使用

原题链接:Leetcode 1584. 连接所有点的最小费用

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

prime:

class Solution {
    
    
public:
    vector<int> d;
    vector<int> visit;
    int cost=0;
    void prime(vector<vector<int>>& points,int t,int n)
    {
    
    
        d[t]=0;
        for(int i=0;i<n;i++)
        {
    
    
            int u=-1,tmp=INT_MAX;
            for(int j=0;j<n;j++)
            {
    
    
                if(!visit[j] && d[j]<tmp)
                {
    
    
                    u=j; tmp=d[j];
                }
            }
            if(u==-1) return ;
            visit[u]=1;
            cost+=d[u];
            for(int j=0;j<n;j++)
            {
    
    
                if(!visit[j])
                {
    
    
                    int dis=abs(points[u][0]-points[j][0])+abs(points[u][1]-points[j][1]);
                    if(dis<d[j]) d[j]=dis;
                }
            }
        }
    }
    int minCostConnectPoints(vector<vector<int>>& points) {
    
    
        int n=points.size();
        d.resize(n,INT_MAX);
        visit.resize(n);
        prime(points,0,n);
        return cost;
    }
};

kruskal: C++ STL之tuple详解

class Solution {
    
    
public:
    static bool cmp(const tuple<int,int,int>& a,const tuple<int,int,int>& b)
    {
    
    
        return get<2>(a) < get<2>(b);
    }
    vector<tuple<int,int,int>> edges;
    map<int,int> fa;
    int findfather(int x)
    {
    
    
        int a=x;
        while(x!=fa[x]) x=fa[x];
        while(a!=fa[a])
        {
    
    
            int z=a;
            a=fa[a];
            fa[z]=x;
        }
        return x;
    }
    int cost=0,num=0;
    void kruskal(int n)
    {
    
    
        for(auto x:edges)
        {
    
    
            int a=get<0>(x),b=get<1>(x),dis=get<2>(x);
            int fx=findfather(a);
            int fy=findfather(b);
            if(fx!=fy) 
            {
    
    
                fa[fy]=fx; 
                cost+=dis;
                num++;
                if(num==n-1) break;
            }              
        }
    }
    int minCostConnectPoints(vector<vector<int>>& points) {
    
    
        int n=points.size();
        for(int i=0;i<n;i++)
        {
    
    
            for(int j=0;j<n;j++)
            {
    
    
                if(j>i)
                {
    
    
                    int dis=abs(points[i][0]-points[j][0])+abs(points[i][1]-points[j][1]);
                    edges.push_back({
    
    i,j,dis});
                    edges.push_back({
    
    j,i,dis});
                }
            }
        }
        for(int i=0;i<n;i++) fa[i]=i;
        sort(edges.begin(),edges.end(),cmp);
        kruskal(n);
        return cost;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_45791939/article/details/128026884