dp(DAG)

rectangle nesting

Time Limit: 3000  ms | Memory Limit: 65535  KB
Difficulty: 4
describe
There are n rectangles, and each rectangle can be described by a, b, representing the length and width. Rectangle X(a,b) can be nested in rectangle Y(c,d) if and only if a<c,b<d or b<c,a<d (equivalent to rotating X90 degrees). For example (1,5) can be nested within (6,2) but not within (3,4). Your task is to pick as many rectangles as possible in a row such that every rectangle except the last can be nested inside the next rectangle.
enter
The first line is a positive number N (0<N<10), indicating the number of test data groups, and
the first line of each group of test data is a positive positive number n, indicating the number of rectangles in the group of test data ( n<=1000)
followed by n lines, each line has two numbers a, b (0<a, b<100), indicating the length and width of the rectangle
output
Each set of test data outputs a number, indicating the maximum number of rectangles that meet the conditions, and each set of output occupies one line
sample input
1
10
1 2
2 4
5 8
6 10
7 9
3 1
5 8
12 10
9 7
2 2
Sample output

5

The "nestable" relationship between rectangles is a typical binary relationship, which can be modeled with graphs. If rectangle X can be nested inside rectangle Y, we connect a directed edge from X to Y. This directed graph is acyclic, because a rectangle cannot be directly or indirectly nested inside itself. In other words, it's a DAG. Thus, our task is to find the longest path on the DAG.

This is what Zishu said, so now we have transformed the problem, so let me talk about the code now:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 1000 + 5 ;
struct node{
    int x,y;
} a [MAXN];
int n,d[MAXN];
bool G[MAXN][MAXN];
int dp(int i){
    //remember
    if (d[i]!=0) return d[i];
    d[i]=1;
    for(int j = 0;j<n;j++) if (G[i][j]) d[i]=max(d[i],dp(j)+1);
    return d[i];
}
void Solve()
{
    scanf("%d",&n);
    for(int i = 0;i<n;i++)
	{
        scanf("%d %d",&a[i].x,&a[i].y);
        if(a[i].x<a[i].y) swap(a[i].x,a[i].y);
    }
    memset(G,0,sizeof(G));
    for(int i = 0;i<n;i++)
		for(int j = 0;j<n;j++){
        	if (i==j) continue;
        	if (a[i].x<a[j].x&&a[i].y<a[j].y){
            	G[i][j]=1;
        	}
    	}
    int res=0;
    for(int i = 0;i<n;i++){
        memset(d,0,sizeof(d));
        int tm=dp(i);
        res=max(res,tm);
    }
    cout<<res<<endl;
}
intmain()
{
    int T;
	cin>>T;
	while(T--)
    	Solve();
    return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325946770&siteId=291194637
DP