【算法随笔:luogu P3029 Cow Lineup S 】(双指针 | hash | 离散化 | 尺取 | 双端队列)

题目大意:

现有N头牛排成一排,这些牛其中包含M个种类,每个牛有对应的一维坐标。

现在要给这些牛拍一张照片,需要照片中出现所有种类的牛,且保证拍照范围最小

分析:

最小完备(覆盖)子区间

可以用双指针(或双端队列)的尺取法

#include <unordered_map>
#include <array>
#include <cstdio>
#include <algorithm>
#include <limits>
#include <deque>

constexpr auto __MAX__ { static_cast<int>(1e5) * 5 };
typedef struct __node__ {
	int coordinate {};
	int   categary {};
	constexpr bool operator<(__node__ const & other) const noexcept
	{ return coordinate < other.coordinate; }
} node;

std::unordered_map<int, int> counter {};
std::array<node, __MAX__> cows {};
std::deque<node> deq {};
int N {};
int result { std::numeric_limits<int>::max() };
int main(void) {
	std::scanf("%d", &N);
	for(int i {}; i < N; (void) ++ counter[cows[i ++].categary])
		std::scanf("%d%d", &cows[i].coordinate, &cows[i].categary);
	auto types { static_cast<int>(counter.size()) };
	counter.clear();
	std::sort(cows.begin(), cows.begin() + N);
	int current {};
	for(int i {}; i < N; ++i) {
		if(! (counter[cows[i].categary] ++)) ++ current;
		deq.push_back(cows[i]);
		while(counter[deq.front().categary] - 1) {
			-- counter[deq.front().categary];
			deq.pop_front();
		}
		if(current == types) result = std::min(result, deq.back().coordinate - deq.front().coordinate);
	}
	std::printf("%d\n", result);
	return 0;
}

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XNB's Not a Beginner

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值