最近一直在看DAG问题看到嵌套矩阵 默默的发现是DAG类型的问题然后默默的去找了资料看
//这个是我从网上找到的用DAG方法做的嵌套矩形
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#define maxn 1008
using namespace std;
int G[maxn][maxn], a[maxn], b[maxn], d[maxn], n;
int dp(int i)//dp函数去寻找最大值(这个是记忆化DP)
{
int& ans = d[i];
if (ans > 0) return ans;
ans = 1;
for(int j = 1; j <= n; j++) if(G[i][j]) ans = max(ans, dp(j)+1);
return ans;
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
for(int i = 1; i <= n; i++) scanf("%d%d", a+i, b+i);
memset(G, 0, sizeof(G));
for(int i = 1; i <= n; i++)//这步是为了找到在比当前的矩阵小的其他矩阵,这样可以更好的在DP函数找到对象
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;
int ans = -1, t, s;
memset(d, 0, sizeof(d));
for (int i = 1; i <= n; i++)
{
t = dp(i);
if(ans < t)
{
ans = t;
s = i;
}
}
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
printf("%d %d %d\n",i,j,G[i][j]);
for(int i=1;i<=n;i++)
printf("%d\n",d[i]);
}
return 0;
}
下面是我的AC代码(我的思路先排序,然后固定一个开始向下寻找)
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string>
#define max 2000
using namespace std;
int dp[max];
struct q
{
int x,y;
}c[max];
int cmp(struct q a,struct q b)
{
if(a.x!=b.x)
{
return a.x<=b.x;
}
else if(a.x==b.x)
{
return a.y<=b.y;
}
}
int main()
{
int i,n,t,temp,j;
while(~scanf("%d",&t))
{
while(t--)
{
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d%d",&c[i].x,&c[i].y);
if(c[i].x>c[i].y)
{
temp=c[i].x;c[i].x=c[i].y;c[i].y=temp;
}
}
sort(c,c+n,cmp);
dp[0]=1;
for(i=1;i<n;i++)
{
int ans=0;
for(j=0;j<i;j++)
{
if(c[i].x!=c[j].x&&c[i].y>c[j].y&&dp[j]>ans)
{
ans=dp[j];
}
}
dp[i]=ans+1;
}
int z=0;
for(i=0;i<n;i++)
if(dp[i]>z)
{
z=dp[i];
}
printf("%d\n",z);
}
}
return 0;
}