DAG上的动态规划的经典题。设f[i]为从i出发的最长长度。
则动归方程为:f[i]=max(f[i],f[j]+1),j=1~n并且第j个矩形正好能够嵌套住第i个矩形。
虽然动态规划的方程很好写但有很多细节还是要注意的,具体过程看代码:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn=1000+5; int read() { int x=0,f=1; char ch; ch=getchar(); while(ch<'0'||ch>'9') {if(ch=='-') f=-1; ch=getchar();} while(ch>='0'&&ch<='9') {x=x*10+ch-'0'; ch=getchar();} return x*f; } int N,n; int f[maxn]; struct edge { int a,b; bool operator < (const edge& x) const { return a<x.a; } } e[maxn]; bool ok(int x,int y) { if(e[x].a<e[y].a&&e[x].b<e[y].b) return 1; if(e[x].b<e[y].a&&e[x].a<e[y].b) return 1; return 0; } int main() { N=read(); for(int k=1;k<=N;k++) { int i,j; n=read(); for(i=1;i<=n;i++) f[i]=1; for(i=1;i<=n;i++) { e[i].a=read(); e[i].b=read(); if(e[i].a<e[i].b) {int t=e[i].a;e[i].a=e[i].b;e[i].b=t;} } sort(e+1,e+n+1); for(i=n;i>=1;i--) for(j=i;j<=n;j++) { if(ok(i,j)) f[i]=max(f[i],f[j]+1); } int maxx=0; for(i=1;i<=n;i++) maxx=max(maxx,f[i]); printf("%d\n",maxx); } }