HDU 1102 Constructing Roads 最小生成树

题意

最小生成树模板题

思路

我把sort的cmp函数 e1.dis < e2.dis 写成 e1.dis - e2.dis RE了一下午,SAD

传送门

http://acm.hdu.edu.cn/showproblem.php?pid=1102

#include 
#include 
#include 
#include 
#include 

using namespace std;

struct Edge {
public:
    int u;      //边的起点
    int v;      //边的终点
    int dis;    //边的长度
    Edge(){}
    Edge(int _u,int _v,int _dis) {
        u = _u;
        v = _v;
        dis = _dis;
    }
};

class UnionFind {
private:
    int * fa;
    int size;
public: 
    UnionFind(int n) {
        size = n;
        fa = new int[n+1];
        Init();
    }

    ~UnionFind() {
        delete[] fa;
    }

    void Init() {
        for(int i = 1 ; i <= size ; i ++) {
            fa[i] = i;
        }
    }

    int Find(int x) {
        if(fa[x] != x) {
            fa[x] = Find(fa[x]);
        }
        return fa[x];
    }

    bool Union(int x,int y) {
        int fx = Find(x);
        int fy = Find(y);
        if(fx != fy) {
            fa[fx] = fy;
            return true;
        }
        else {
            return false;
        }
    }

    int GetCount() {
        int count = 0;
        for(int i = 1 ; i <= size ; i ++) {
            if(fa[i] == i) {
                count ++;
            }
        }
        return count;
    }

    int GetMaxSetNum() {
        int maxSetNum = 0;
        int * countSet = new int[size+1];
        memset(countSet,0,sizeof(int)*(size+1));
        for(int i = 1 ; i <= size ; i ++) {
            int fi = Find(i);
            countSet[fi] ++;
        }
        for(int i = 1 ; i <= size ; i ++) {
            if(countSet[i] > maxSetNum) {
                maxSetNum = countSet[i];
            }
        }
        delete[] countSet;
        return maxSetNum;
    }
};

#define MAXE 10005
#define MAXN 105

bool cmp(Edge e1,Edge e2) {
    return e1.dis < e2.dis;
}

int main(void) {
    // freopen("a.in","r",stdin);
    int n ;
    Edge * edge = new Edge[MAXE];
    while(~scanf("%d",&n)) {
        UnionFind uf(MAXN);
        int tot = 0;
        for(int i = 1 ; i <= n ; i++) {
            for(int j = 1 ; j <= n ; j++) {
                int dis;
                scanf("%d",&dis);
                if(j > i) {
                    // Edge e(i,j,dis);
                    edge[tot].u = i;
                    edge[tot].v = j;
                    edge[tot].dis = dis;
                    tot = tot + 1; 
                }
            }
        }
        int m;
        scanf("%d",&m);
        for(int i = 0 ; i < m ; i ++) {
            int u,v;
            scanf("%d %d",&u,&v);
            uf.Union(u,v);
        }
        sort(edge,edge+tot,cmp);

        int ret = 0;
        // printf("%d\n",tot);
        for(int i = 0 ; i < tot ; i ++) {
            if(true == uf.Union(edge[i].u,edge[i].v)) {
                ret += edge[i].dis;
            }
        }
        printf("%d\n",ret);
    }
    // delete[] edge;
    return 0;
}

你可能感兴趣的:(图论500题)