【题解】Constructing Roads POJ - 2421(最小生成树 Kruskal) ⭐⭐⭐

Constructing Roads POJ - 2421

有N个村庄,从1到N,你应该修建一些道路,这样每两个村庄就可以连接起来。我们说两个村庄A和B相连,当且仅当A和B之间有一条路,或者存在一个村庄C使得A和C之间有一条路,并且C和B相连。我们知道一些村庄之间已经有一些道路了,你的工作是修建一些道路,这样所有的村庄都连接起来,所有道路的长度都是最小的。

Input

第一行是整数N (3 <= N <= 100),即村庄数。然后是N行,第i行包含N个整数,第j行是村i和村j之间的距离(距离应该是[1,1000]内的整数)。然后是整数Q (0 <= Q <= N * (N + 1) / 2),然后是Q行,每一行包含两个整数a和b (1 <= a < b <= N),这意味着a村和b村之间的道路已经建成。

Output

您应该输出一条包含整数的线,该整数是所有要修建的道路的长度,以便所有村庄都连接起来,并且该值是最小的。

Examples

Sample Input
3
0 990 692
990 0 179
692 179 0
1
1 2
Sample Output
179

Hint




题意:

开始我可能对题意的理解有点误区, 注意"我们说两个村庄A和B相连,当且仅当A和B之间有一条路,或者存在一个村庄C使得A和C之间有一条路,并且C和B相连。"这句话, 是要递归着去理解的, 其实就是最小生成树的定义

题解:

对于题目中给出的点我们先预处理一下, 因为是稠密图而且侧重对边的处理, 我们使用Kruskal

经验小结:


#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef  long long LL;
const int inf = 1 << 30;
const LL maxn = 110;

int par[maxn], rak[maxn];
void init(int n) {
    for(int i = 0; i < n; i++)
        par[i] = i, rak[i] = 0;
}
int findr(int x) {
    if(x == par[x])
        return x;
    else
        return par[x] = findr(par[x]);
}
bool isSame(int x, int y) {
    return findr(x) == findr(y);
}
void unite(int x, int y) {
    x = findr(x), y = findr(y);
    if(x == y)
        return;
    if(rak[x] < rak[y])
        par[x] = y;
    else {
        par[y] = x;
        if(rak[x] == rak[y])
            ++rak[x];
    }
}

struct Edge {
    int u, v, w;
    Edge(int uu, int vv, int ww) {
        u = uu, v = vv, w = ww;
    }
    Edge() {
        u = 0, v = 0, w = inf;
    }
} es[maxn * maxn];
bool cmp(const Edge &a, const Edge &b) {
    return a.w < b.w;
}
int V, E = 0; //顶点数和边数
int Kruskal() {
    sort(es, es + E, cmp); //对边排序
    int ret = 0;
    for(int i = 0; i < E; i++) {
        Edge cur = es[i];
        if(!isSame(cur.u, cur.v)) {
            unite(cur.u, cur.v);//只要不是同一连通分量即归入生成树
            ret += cur.w;
        }
    }
    return ret;
}
int main() {
    cin >> V;
    init(V);
    int w, q, a, b;
    for(int u = 1; u <= V; u++) {
        for(int v = 1; v <= V; v++) {
            cin >> w;
            es[E++] = Edge(u, v, w);
        }
    }
    cin >> q;
    while(q--){
        cin >> a >> b;
        if(!isSame(a, b))
            unite(a, b);
    }
    cout << Kruskal() << endl;

    return 0;
}

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