CF4D
题目描述
给卡片宽高和 n 个信封的宽高,选出尽可能多的信封排成链,要求每个信封的宽和高都严格大于前一个。卡片必须能放进最小的信封里。求最长链的长度并输出方案。
解题思路
神秘DP/yun。进行了一个二维最长上升子序列大学习·-·。
首先进行预处理,过滤掉宽或高小于等于卡片对应值的信封,这些无法作为链的任一环节。
将剩余信封按宽度以第一关键字 高度以第二关键字升序排序。排序后,宽度条件通过枚举时判断 a[j].w < a[i].w 保证严格递增,问题就转化成了二维最长上升子序列。
对每个信封 i,枚举<i的j,如果j的宽度和高度均严格小于 i,则 f[i] = max(f[i], f[j] + 1),同时更新las[i]=j。
最后找出f值最大的位置,递归输出完整的路径。
Code
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=5010;
int n,f[N],las[N],wz,hz,cnt;
struct node{
int w,h,id;
}a[N];
bool cmp(const node&fir,const node&sec){
if(fir.w^sec.w) return fir.w<sec.w;
return fir.h<sec.h;
}
void outit(int k){
if(k==-1) return;
outit(las[k]); cout<<a[k].id<<" ";
}
signed main(){
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
ios::sync_with_stdio(0),cin.tie(0);
cin>>n>>wz>>hz;
for(int i=1;i<=n;i++){
int w,h;cin>>w>>h;las[i]=-1;
if(w<=wz||h<=hz) continue;
a[++cnt].w=w;a[cnt].h=h;a[cnt].id=i;
}
if(cnt==0){cout<<"0\n";return 0;}
sort(a+1,a+cnt+1,cmp);
for(int i=1;i<=cnt;i++){
f[i]=1;
for(int j=1;j<i;j++){
if(a[j].w<a[i].w&&a[j].h<a[i].h&&f[j]+1>f[i]){
f[i]=f[j]+1;
las[i]=j;
}
}
}
int ans=0,flag=0;
for(int i=1;i<=cnt;i++){
if(f[i]>ans){
ans=f[i];
flag=i;
}
}
cout<<ans<<"\n";
outit(flag);
return 0;
}