具有最优子结构性质,按照从小到大排序。
用dp[]表示当前最大嵌套数,初始值为1。
用二次循环寻找当前最大嵌套数。
#include <iostream>
#include <algorithm>
#include <cstring>
#define maxn 1001
using namespace std;
struct rect{
int x,y;
}k[maxn];
bool cmp(rect a,rect b){
if(a.x==b.x) return a.y<b.y;
return a.x<b.x;
}
int dp[maxn];
int main(){
int test_num;
cin>>test_num;
while(test_num--){
memset(dp,0,sizeof(dp));
int rect_num;
cin>>rect_num;
for(int i=0;i<rect_num;i++){
cin>>k[i].x>>k[i].y;
if(k[i].x>k[i].y)
swap(k[i].x,k[i].y);
}
sort(k,k+rect_num,cmp);
int max_num=0;
for(int i=0;i<rect_num;i++){
dp[i]=1;
for(int j=0;j<i;j++){
if(k[i].x>k[j].x&&k[i].y>k[j].y&&dp[j]+1>dp[i]){
dp[i]=dp[j]+1;
}
}
}
for(int i=0;i<rect_num;i++)
max_num=max(max_num,dp[i]);
cout<<max_num<<endl;
}
}