思路:
采用并查集联通
步骤:
1.建图,每个点向右边点,下边点连边,权值为两者差的绝对值
2.将边权从小到大排序
3.不断加边进来,当合并的集合中点的个数 个, 则最新加入的边权 集合中的点数即为答案
4.将集合中出发点个数清零
AC代码:
#include <bits/stdc++.h>
using namespace std;
long long m, n, t, cp, ce, ans, h[505][505], s[505][505], id[505][505], fa[500005], tot[500005], ts[500005];
struct node {
long long w, x, y;
}a[500005];
bool cmp(node a, node b) {
return a.w < b.w;
}
int find(int x) {
if(fa[x] == x)
return x;
return fa[x] = find(fa[x]);
}
int main() {
cin >> m >> n >> t; //行、列、格子数量的要求
for(int i = 1; i <= m; i++)
for(int j = 1; j <= n; j++)
cin >> h[i][j]; //海拔
for(int i = 1; i <= m; i++)
for(int j = 1; j <= n; j++)
cin >> s[i][j]; //起点
for(int i = 1; i <= m; i++)
for(int j = 1; j <= n; j++)
id[i][j] = ++cp, ts[cp] = s[i][j]; //二维降一维编号, cp是点的数量
//ts表示当前集合起点数量,每个编号的点初始化为一个集合
for(int i = 1; i <= m; i++)
for(int j = 1; j <= n; j++) {
if(i != m) //向下建边
ce++, a[ce].x = id[i][j], a[ce].y = id[i + 1][j], a[ce].w = abs(h[i][j] - h[i + 1][j]);
if(j != n) //向右建边
ce++, a[ce].x = id[i][j], a[ce].y = id[i][j + 1], a[ce].w = abs(h[i][j] - h[i][j + 1]);
} //ce是边的数量
for(int i = 1; i <= cp; i++) //所有的点初始化
fa[i] = i, tot[i] = 1; //tot记录当前集合中的总点数
sort(a + 1, a + ce + 1, cmp); //边排序
for(int i = 1; i <= ce; i++) { //枚举所有的边
int fx = find(a[i].x);
int fy = find(a[i].y);
if(fx != fy) {
fa[fx] = fy, ts[fy] += ts[fx], tot[fy] += tot[fx], ts[fx] = tot[fx] = 0;
//fy设为fx的祖先,维护fy的"起点"的数量,fx不再是一个祖先,已合并到fy, 集合数量清零,维护fy的总点数
if(tot[fy] >= t)
ans += ts[fy] * a[i].w, ts[fy] = 0; //当前集合的难度系数和 = 起点数量 * 难度系数
//计算过的起点删除
}
}
cout << ans;
return 0;
}