题目
描述 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,yx,y,格子为n∗mn * mn∗m的,那么当前点的坐标=(x−1)∗m+n=(x - 1)* m + n=(x−1)∗m+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;
}