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

这道题的贪心策略就是每次都选能阻碍最多的横线或者纵线,我们可以把每个位置和阻隔学生数量绑定在一起,可能会想到哈希表或者数组,但是我们还要根据阻隔学生数量进行排序,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;
}
相关推荐
空中海1 天前
iOS 动态分析、抓包与 Frida Hook
ios·职场和发展·蓝桥杯
knight_9___1 天前
LLM工具调用面试篇5
人工智能·python·深度学习·面试·职场和发展·llm·agent
陈序缘1 天前
AI Agent 的道与术
人工智能·职场和发展·agi
浅念-1 天前
吃透栈:LeetCode 栈算法题全解析
数据结构·c++·算法·leetcode·职场和发展·
qeen871 天前
【算法笔记】简单贪心
c++·笔记·算法·贪心算法
逻辑驱动的ken1 天前
Java高频面试考点场景题21
java·开发语言·面试·职场和发展·求职招聘
穿条秋裤到处跑1 天前
每日一道leetcode(2026.04.29):二维网格图中探测环
算法·leetcode·职场和发展
汉克老师2 天前
GESP2025年3月认证C++五级( 第三部分编程题(1、平均分配))
c++·算法·贪心算法·排序·gesp5级·gesp五级
Morwit2 天前
QML组件之间的通信方案(暴露子组件)
c++·qt·职场和发展
leoufung2 天前
LeetCode 76:Minimum Window Substring 题解与滑动窗口思维详解
算法·leetcode·职场和发展