Rectangular nesting time limit: 3000 MS | memory limit: 65535 kb difficulty: 4
-
Description
-
There are n rectangles. Each rectangle can be described by a and B to indicate length and width. Rectangle X (A, B) can be nested in Rectangle y (c, d) When and only when a <C, B <D or B <C, A <D (equivalent to rotating x 90 degrees ). For example, () can be nested in (), but cannot be nested in. Your task is to select as many rectangles as possible and arrange them in one row so that, except the last one, each rectangle can be nested in the next rectangle.
-
Input
-
The first line is a positive number N (0 <n <10), indicating the number of test data groups,
The first row of each group of test data is a positive number N, indicating the number of rectangles in the group of test data (n <= 1000)
The next n rows have two numbers a and B (0 <a, B <100), indicating the length and width of the rectangle.
-
Output
-
Each group of test data outputs one number, indicating the maximum number of rectangles that meet the conditions. Each group of output occupies one row.
-
Sample Input
-
1101 22 45 86 107 93 15 812 109 72 2
-
Sample output
-
5
Dynamic Planning:
AC code:
#include <iostream>#include <string.h>using namespace std;int G[1010][1010];int d[1010];int dp(int i,int n){int &ans=d[i];if(ans>0) return ans;ans=1;for(int j=1;j<=n;j++)if(G[i][j]) if(ans<dp(j,n)+1)ans=dp(j,n)+1;return ans;}int main(){int N;cin>>N;while(N--){int n,a[1010],b[1010];memset(G,0,sizeof(G));memset(d,0,sizeof(d));cin>>n;for(int i=1;i<=n;i++)cin>>a[i]>>b[i];for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)if((a[i]>a[j]&&b[i]>b[j])||(a[i]>b[j]&&b[i]>a[j])) G[i][j]=1;//for(int i=0;i<n;i++)//for(int j=0;j<n;j++)//if(G[i][j]) cout<<i<<"-->"<<j<<endl;int max=0;for(int i=1;i<=n;i++)if(dp(i,n)>max) max=dp(i,n);cout<<max<<endl;}return 0;}
Sequence of output results:
#include <iostream>#include <string.h>using namespace std;int G[1010][1010];int d[1010];int n;int dp(int i){int &ans=d[i];if(ans>0) return ans;ans=1;for(int j=1;j<=n;j++)if(G[i][j]) if(ans<dp(j)+1)ans=dp(j)+1;return ans;}void print_ans(int i){printf("%d ",i);for(int j=1;j<=n;j++) if(G[i][j]&&d[i]==d[j]+1){print_ans(j);break;}}int main(){int N;cin>>N;while(N--){int a[1010],b[1010];memset(G,0,sizeof(G));memset(d,0,sizeof(d));cin>>n;for(int i=1;i<=n;i++)cin>>a[i]>>b[i];for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)if((a[i]>a[j]&&b[i]>b[j])||(a[i]>b[j]&&b[i]>a[j])) G[i][j]=1;//for(int i=0;i<n;i++)//for(int j=0;j<n;j++)//if(G[i][j]) cout<<i<<"-->"<<j<<endl;int max=0,max_i=0;for(int i=1;i<=n;i++)if(dp(i)>max) {max=dp(i);max_i=i;}print_ans(max_i);cout<<endl;}return 0;}
Result: