蓝桥杯备考:贪心算法之排座椅

这道题的贪心策略就是每次都选能阻碍最多的横线或者纵线,我们可以把每个位置和阻隔学生数量绑定在一起,可能会想到哈希表或者数组,但是我们还要根据阻隔学生数量进行排序,so我们得开个结构体,然后写个cmp来规定排序才好,最后再把排好序的,如果阻隔数量相等的,按位置从小到大排序,也就是说我们需要排两次序

好的,我们来写一下代码吧

cpp 复制代码
#include <iostream>
#include <algorithm>
const int N = 1010;

using namespace std;

int n,m,k,l,d;

struct node{
	int x;
	int cnt;
}col[N],row[N];
bool cmp1(const node& p1,const node& p2)
{
	return p1.cnt>p2.cnt;
}
bool cmp2(const node &p1,const node& p2)
{
	return p1.x < p2.x;
}
int main()
{
	cin >> n >> m >> k >> l >> d;
	for(int i = 1;i<=m;i++)
	{
		col[i].x = i;
	}
	for(int i = 1;i<=n;i++)
	{
		row[i].x = i;
	}
	while(d--)
	{
		int x1,y1,x2,y2;
		cin >> x1 >> y1 >> x2 >> y2;
		if(x1==x2) col[min(y1,y2)].cnt++;
		else if(y1==y2) row[min(x1,x2)].cnt++;
	}
	sort(col+1,col+1+m,cmp1);
	
	sort(row+1,row+1+n,cmp1);
	
	sort(col+1,col+1+l,cmp2);
	sort(row+1,row+1+k,cmp2);
	
	for(int i = 1;i<=k;i++)
	{
		cout << row[i].x << " ";
		
	}
	cout << endl;

	for(int i = 1;i<=l;i++)
	{
		cout << col[i].x << " ";
		
	}
	cout << endl;

	
	return 0;
}
相关推荐
驭渊的小故事15 小时前
LeetCode 算法题解:滑动窗口与数组合并的实战应用
算法·leetcode·职场和发展
八月的雨季 最後的冰吻17 小时前
音视频面试--延迟优化
面试·职场和发展·音视频
Pniubi18 小时前
力扣42接雨水(动态规划法)
算法·leetcode·职场和发展
weixin_3077791318 小时前
RAG 级联失效分析——面试中的错误归因艺术
人工智能·python·面试·职场和发展
Pniubi18 小时前
力扣46全排列(回溯(递归))
算法·leetcode·职场和发展
Pniubi1 天前
力扣283移动零(双指针法)
算法·leetcode·职场和发展
frjc2 天前
分布式服务拆分实战指南:从底层逻辑到面试话术
微服务·面试·职场和发展
UIU1142 天前
P16237 [蓝桥杯 2026 省 B] 应急布线
数据结构·c++·算法·蓝桥杯
H_BB2 天前
面试笔记:数据加密和心跳机制
笔记·面试·职场和发展
Pniubi2 天前
力扣543二叉树的直径(深度优先搜索法(递归))
算法·leetcode·职场和发展