连接格点

点阵连通最小花费算法
本文介绍了一种解决点阵连通问题的算法,通过将二维坐标转换为一维并使用并查集,实现计算最少花费使所有点连通。输入包含点阵大小和已连线段,输出为最小花费。

题目

描述 Description
有一个M行N列的点阵,相邻两点可以相连。一条纵向的连线花费一个单位,一条横向的连线花费两个单位。某些点之间已经有连线了,试问至少还需要花费多少个单位才能使所有的点全部连通。
输入格式 Input Format
第一行输入两个正整数m和n。
  以下若干行每行四个正整数x1,y1,x2,y2,表示第x1行第y1列的点和第x2行第y2列的点已经有连线。输入保证|x1-x2|+|y1-y2|=1。
输出格式 Output Format
输出使得连通所有点还需要的最小花费。
样例输入 Sample Input
2 2
1 1 2 1
样例输出 Sample Output
3
时间限制 Time Limitation
3s
注释 Hint
数据规模
  m,n<=1000

题解

把坐标换成一个数,然后用并查集来做。
关于坐标换数,就是把一个二维的数组展成一维的。
设当前点为x,yx,yxy,格子为n∗mn * mnm的,那么当前点的坐标=(x−1)∗m+n=(x - 1)* m + n=x1m+n;(手动模拟一下就很好理解)。
根据贪心的思想,做并差集时先合并竖列在合并横列。、

code

#include <algorithm>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstring>
#include <deque>
#include <functional>
#include <list>
#include <map>
#include <iomanip>    
#include <iostream>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>

typedef long long ull;
const int maxn = 1e6 + 1000;
const int inf = 0x3f3f3f3f;

inline int read() {
    int s = 0, w = 1;
    char ch = getchar();
    while (!isdigit(ch)) { if (ch == '-') w = -1; ch = getchar(); }
    while (isdigit(ch)) { s = (s << 1) + (s << 3) + (ch ^ 48); ch = getchar(); }
    return s * w;
}

int m;
int n;
int xa;
int ya;
int xb;
int yb;
int ans;
int f[maxn];

inline int find(int k) { 
    return f[k] == k ? k : f[k] = find(f[k]);
}

inline int getpos(int x, int y) { 
    return (x - 1) * n + y; 
}

inline int unio(int x, int y) { 
    int xx = find(x), yy = find(y);
    if (xx != yy) {
        f[yy] = xx;
        return 1;
    }
    return 0;
}

int main() {
    m = read(), n = read(); 
    ans = 0;
    for (int i = 1; i <= n * m; ++i) f[i] = i;
    while (scanf("%d %d %d %d", &xa, &ya, &xb, &yb) == 4) {
         int u = getpos(xa, ya), v = getpos(xb, yb);
         unio(u, v);
    }
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j < m; ++j) {
            if (unio( getpos(j, i), getpos(j + 1, i) )) {
                ++ans;
            }
        }
    }
    for (int i = 1; i <= m; ++i) {
        for (int j = 1; j < n; ++j) {
            if (unio( getpos(i, j), getpos(i, j + 1) )) {
                ans += 2;
            }
        }
    }
    printf("%d\n", ans);
    // system("PAUSE");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值