第一周 A - Cleaning Shifts

本文深入解析了一种常见的算法问题——区间覆盖,通过poj2376题目为例,详细介绍了如何利用C++实现区间覆盖问题的解决策略。文章提供了一份完整的代码示例,并通过实例解释了算法的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我真的是太菜了,这道题让我想了好久,最后看别人的解说才明白是区间覆盖问题。

源自poj2376

这道题就是一个套路。。。。

#include <iostream>
#include<cstdio>
#include <algorithm>
using namespace std;
const int MAX = 1e6 + 10;
struct P
{
 int x, y;
};
int n, t;
P num[MAX];
bool cmp(P x, P y)
{
 if (x.x == y.x) return x.y < y.y;
 return x.x < y.x;
}
int main()
{
 cin >> n >> t;
 bool start = false, end = false;
 for (int i = 1; i <= n; i++)
 {
  scanf_s("%d%d", &num[i].x, &num[i].y);
  if (num[i].x == 1) start = true;
  if (num[i].y == t)end = true;
 }
 sort(num + 1, num + n + 1, cmp);
 if (!start || !end) { cout << -1 << endl; return 0; }
 int pos = 1, tmp = 1, right = 0; int ans = 0;
 while (true)
 {
  //cout << tmp << endl;
  while (pos <= n && num[pos].x <= right + 1)
  {
   if (num[pos].y > tmp) tmp = num[pos].y; pos++;
  }
  if (right != tmp)
  {
   right = tmp; ans++;
   if (right >= t) break;
  }
  else
  {
   cout << -1 << endl; return 0;
  }
 }
 cout << ans << endl;
 return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值