# DP动态规划-嵌套矩形

DAG（有向无环图）模型可以解决很多动态规划的问题。很多问题可以转化成DAG上的最长路径、最短路径或路径计数问题。

#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE	100
typedef struct {
int length;
int width;
}Rectangle;
int G[MAXSIZE][MAXSIZE];
Rectangle rec[MAXSIZE];
int n;//矩形数
int count;
//a可以嵌套在b中
int isInside(Rectangle a, Rectangle b)
{
return (a.length < b.length && a.width < b.width
|| a.length < b.width && a.width < b.length) ? 1 : 0;
}
void dp(int row, int length)
{
if(length > count)
count = length;
printf("length=%d\n", length);
for(int j = 0; j < n; j++)
{
if(G[row][j] > 0)
{
printf("%d->%d\n", row, j);
dp(j, length + 1);
}
}
}
int main()
{
scanf("%d", &n);
int i = 0;
while(i < n)
scanf("%d%d", &rec[i].length, &rec[i++].width);
for(i = 0; i < n; i++)
for(int j = 0; j < n; j++)
G[i][j] = isInside(rec[i], rec[j]);
int max = 0;
for(i = 0; i < n; i++)
{
count = 0;
printf("begin from rect %d\n", i);
dp(i, 1);
if(count > max)
max = count;
}
printf("%d\n", max);
system("pause");
}
/*
10
1 2
2 4
5 8
6 10
7 9
3 1
5 8
12 10
9 7
2 2
output
5
*/