题目描述
描述 Description
有一个M行N列的点阵,相邻两点可以相连。一条纵向的连线花费一个单位,一条横向的连线花费两个单位。某些点之间已经有连线了,试问至少还需要花费多少个单位才能使所有的点全部连通。
输入格式 Input Format
第一行输入两个正整数m和n。
以下若干行每行四个正整数x 1 , y 1 , x 2 , y 2 x1,y1,x2,y2x1,y1,x2,y2,表示第x1行第y1列的点和第x2行第y2列的点已经有连线。输入保证∣ x 1 − x 2 ∣ + ∣ y 1 − y 2 ∣ = 1 |x1-x2|+|y1-y2|=1∣x1−x2∣+∣y1−y2∣=1。
输出格式 Output Format
输出使得连通所有点还需要的最小花费。
样例输入
2 2
1 1 2 1
样例输出
3
时间限制
3s
#include<bits/stdc++.h>
using namespace std; using ll = long long;
int dir[4][2] = { 1, 0, -1, 0, 0, 1, 0, -1 };
const int N = 3e6 + 10, mod = 1e9 + 7, INF = 0x3f3f3f3f;
int n, m, f[N], cnt;
class Edge {
public:
int x, y, d;
};
vector<Edge> edges;
int getf(int x) {
return x == f[x] ? x : f[x] = getf(f[x]);
}
bool merge(int u, int v) {
int t1 = getf(u), t2 = getf(v);
if (t1 == t2) return false;
if (t1 > t2) swap(t1, t2);
f[t2] = t1;
return true;
}
inline int getid(int x, int y) {
return x * n - n + y;
}
int kruskal() {
ll res = 0;
for (auto& [x, y, d] : edges) {
cout << x << " " << y << endl;
if (merge(x, y)) {
res += d;
cnt++;
}
if (cnt == n * m - 1)
return res;
}
return -1;
}
void init() {
cin >> m >> n;
for (int i = 1; i <= m * n; i++) {
f[i] = i;
}
int x1, y1, x2, y2;
while (cin >> x1 >> y1 >> x2 >> y2)
cnt += merge(getid(x1, y1), getid(x2, y2));
return;
}
void solve() {
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (i < m)
edges.emplace_back(getid(i, j), getid(i + 1, j), 1);
}
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (j < n)
edges.emplace_back(getid(i, j), getid(i, j + 1), 2);
}
}
cout << kruskal();
return;
}
int main(void) {
ios::sync_with_stdio(0); cin.tie(0); cout << setprecision(6) << fixed;
int TT = 1;
//cin >> TT;
for (int ii = 1; ii <= TT; init(), solve(), ii++, cout << "\n") {}
return 0;
}