区间合并+并查集

前言:写完这个题目的时候没意识到这个和区间合并是等价的,现在看起来确实是一个区间合并的题目

(注意这个多米诺骨牌是可以连续推倒的)


cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

#define int long long
int t;
int n,m;
const int N = (int)2e5+5;
struct node{
	int h,pos;
	bool operator<(node b){
		return pos < b.pos;
	}
}sto[N];
int fa[N];
int find(int x){
	if(x==fa[x]) return x;
	return fa[x] = find(fa[x]);
}
int ans[N];

bool cmp(int a,int b){
	return a>b;
}

signed main(){
	cin >> t;
	while(t--){
		cin >> n >> m;
		for(int i=1;i<=n;i++){
			cin >> sto[i].h;
		}
		for(int i=1;i<=n;i++){
			cin >> sto[i].pos;
		}
		sort(sto+1,sto+1+n);
		for(int i=1;i<=n;i++) fa[i] = i;
		int j;
		for(int i=1;i<=n;i=j){
			int hi = sto[i].h, posi= sto[i].pos;
			int en = hi + posi;
			for(j=i+1;j<=n;j++){
				int hj = sto[j].h, posj = sto[j].pos;
				if(en>=posj){  // 如果能够到达 
					fa[j] = i;
					//更新我们的长度
					en = max(en,hj+posj); 
				}else{
					break;
				}
			}
		}
		for(int i=1;i<=n;i++) ans[i] = 0;
		for(int i=1;i<=n;i++){
			int x = find(i);
			//cout << " i " << x << endl;
			ans[x]++;
		}

		sort(ans+1,ans+1+n,cmp);
		int e = 0;
		//cout << " ans 1 " << ans[1] << endl;
		for(int i=1;i<=m;i++){
			e+=ans[i];
		}
		cout << e << endl;
	}
	return 0;
}
相关推荐
JieE21221 小时前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack201 天前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树1 天前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2122 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2122 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术2 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦2 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
clint4562 天前
C++进阶(1)——前景提要
c++
用户497863050732 天前
(一)小红的数组操作
算法·编程语言