题目描述
一堆木头棍子共有n根,每根棍子的长度和宽度都是已知的。棍子可以被一台机器一个接一个地加工。机器处理一根棍子之前需要准备时间。准备时间是这样定义的:
第一根棍子的准备时间为1分钟;
如果刚处理完长度为L,宽度为W的棍子,那么如果下一个棍子长度为Li,宽度为Wi,并且满足L>=Li,W>=Wi,这个棍子就不需要准备时间,否则需要1分钟的准备时间;
计算处理完n根棍子所需要的最短准备时间。比如,你有5根棍子,长度和宽度分别为(4, 9),(5, 2),(2, 1),(3, 5),(1, 4),最短准备时间为2(按(4, 9)、(3, 5)、(1, 4)、(5, 2)、(2, 1)的次序进行加工)。
输入格式
第一行是一个整数n(n<=5000),第2行是2n个整数,分别是L1,W1,L2,w2,…,Ln,Wn。L和W的值均不超过10000,相邻两数之间用空格分开。
输出格式
仅一行,一个整数,所需要的最短准备时间。
输入输出样例
输入 #1复制
5 4 9 5 2 2 1 3 5 1 4输出 #1复制
2
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
// 解题思路:
// 当长度和宽度大于下一木棍时,则不需要准备时间,即长宽构成的矩形覆盖
// 那么先对长度或宽度排序,再对另一未顺序排列的属性求最长上升子序列,其长度则是需要的准备时间
// 这样就转化成了求最大上升子序列的问题
const int maxn = 5e3 + 5;
inline void read(int &x)
{
register int f = 1; x= 0;
register char c = getchar();
while(c > '9' || c < '0')
{
if(c == '-') f = -1;
c = getchar();
}
while(c >= '0' && c <= '9')
{
x = (x << 3) + (x << 1) + (c ^ 48);
c = getchar();
}
x *= f;
}
struct node
{
int id, l, w;
// 重载运算符,长度大的在前,相等则宽度大的在前
bool operator<(const node &rhs) const
{
if(this->l != rhs.l)
return this->l > rhs.l;
else
return w > rhs.w;
}
};
// 容器
vector<node> v;
// 用来求最长上升子序列
int dp[maxn];
int main()
{
// 读入数据
int n; read(n);
for(int l, w, i = 1; i <= n; i++)
{
read(l); read(w);
v.push_back((node){i, l, w});
}
// 排序
sort(v.begin(), v.end());
// 求最长上升子序列
int len(0);
for(int i = 0; i < v.size(); i++)
{
// 大于则末尾插入
if(v[i].w > dp[len])
{
dp[++len] = v[i].w;
}
// 否则寻找位置替换,更新为更容易增长的状态
else
{
int s = lower_bound(dp + 1, dp + len + 1, v[i].w) - dp;
dp[s] = v[i].w;
}
// printf("%d %d %d\n", v[i].id, v[i].l, v[i].w);
}
// 输出长度则是需要的准备时间
printf("%d\n", len);
return 0;
}