Description
一堆木头棍子共有 n n n根,每根棍子的长度和宽度都是已知的。棍子可以被一台机器一个接一个地加工。机器处理一根棍子之前需要准备时间。准备时间是这样定义的:
第一根棍子的准备时间为 1 1 1分钟;
如果刚处理完长度为 L L L,宽度为 W W W的棍子,那么如果下一个棍子长度为 L i L_i Li,宽度为 W i W_i Wi,并且满足 L > = L i L>=L_i L>=Li, W > = W i W>=W_i W>=Wi,这个棍子就不需要准备时间,否则需要 1 1 1分钟的准备时间;
计算处理完 n n n根棍子所需要的最短准备时间。比如,你有5根棍子,长度和宽度分别为 ( 4 , 9 ) , ( 5 , 2 ) , ( 2 , 1 ) , ( 3 , 5 ) , ( 1 , 4 ) (4, 9),(5, 2),(2, 1),(3, 5),(1, 4) (4,9),(5,2),(2,1),(3,5),(1,4),最短准备时间为 2 2 2(按 ( 4 , 9 ) 、 ( 3 , 5 ) 、 ( 1 , 4 ) 、 ( 5 , 2 ) 、 ( 2 , 1 ) (4, 9)、(3, 5)、(1, 4)、(5, 2)、(2, 1) (4,9)、(3,5)、(1,4)、(5,2)、(2,1)的次序进行加工)。
Input
第一行是一个整数 n ( n < = 5000 ) n(n<=5000) n(n<=5000),第 2 2 2行是 2 n 2n 2n个整数,分别是 L 1 , W 1 , L 2 , w 2 , … , L n , W n L_1,W_1,L_2,w_2,…,L_n,W_n L1,W1,L2,w2,…,Ln,Wn。 L L L和 W W W的值均不超过 10000 10000 10000,相邻两数之间用空格分开。
Output
仅一行,一个整数,所需要的最短准备时间。
Solution
1.不会证/没听过的定理:dilworth定理
定理总结:不下降子序列最小个数等于最大上升子序列的长度。
2.因此,答案简化为求最长上升子序列。
本题采用 O ( n l o g n ) O(n\,log\,n) O(nlogn)做法,但 O ( n 2 ) O(n^2) O(n2)也同样可行。
Code
/*************************************
* @problem: problem title.
* @author: iamshroud.
* @time: 2021-??-??.
*************************************/
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
// #include <unordered_map>
typedef long long ll;
#define itn int //ovo
#define MOD 1000000007
using namespace std;
inline ll read()
{
ll x=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
while (ch>='0'&&ch<='9'){x=x*10+ch-48;ch=getchar();}
return x*f;
}
ll n;
struct node
{
ll l, w;
}arr[5005];
ll dp[5005];
bool cmp(node a , node b)
{
if(a.l != b.l)
return a.l > b.l;
return a.w > b.w;
}
void solve()
{
n = read();
for(int i=1; i<=n; i++)
{
arr[i].l = read(), arr[i].w = read();
}
sort(arr+1, arr+n+1, cmp);
ll ans = 0;
// O(n log n)求最长上升子序列
for(int i=1; i<=n; i++)
{
// 由于排序下l严格从大到小
// 因此只需要比较w即可
if(arr[i].w > dp[ans])
{
dp[++ans] = arr[i].w;
}
else
{
int pt = lower_bound(dp+1, dp+ans+1, arr[i].w)-dp;
dp[pt] = arr[i].w;
}
}
//根据dilworth定理
//不下降子序列最小个数等于最大上升子序列的长度
cout << ans;
}
int main(void)
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
// come on
solve();
return 0;
}