Background
I was looking at some programming Olympiads the other day, and I found this ACM-ICPC Ukraine 2013 pdf.
The part I am working on is Problem D, which consist of finding out how many rectangle can you nest within another rectangle.
Assume a sequence of \$N\$ rectangles \$a_1 \times b_1,a_2\times b_2, ..., a_N \times b_N\$ where each \$ N \to a_N≤b_N \$.
Rectangle \$ a_i×b_i \$ can be put inside rectangle \$ a_k×b_k \$ if \$ (a_i<a_k)\land(b_i<b_k)\$.
We call sequence of rectangles nesting sequence, if each rectangle can be put inside following one.
The task is to write a program that finds the longest nesting subsequence, i. e. the longest nesting sequence among all subsequences of the given sequence.
Note: Rectangles is not to be rotated.
Input
First line of input is \$ N \$ with positive integer no more than 100.000.
The next subsequent inputs are\$ N \$ two integers \$ a_i b_i (1≤a_i≤b_i≤10^9) \$ as the size of the rectangle.
Output
Exactly 1 output, the length of the longest subsequence.
Sample
INPUT | Output
------- | _______
5 | 3
10 10 |
3 7 |
5 5 |
4 9 |
12 12 |
Where the sequence is assumed to be \$ 3×7, 4×9, 12×12 \$
Limits
Time limit is to be less than 2 seconds, with maximum memory usage of 64 MB, based on input specifications.
Code
I figured this must be a Longest Increasing Subsequence with the twist of rectangles quiz, and I got the correct output based on the prompt.
However I am not too sure of the code, code review is appreciated!
#include <stdio.h>
#define MAX_ITEMS 100000
struct Rectangle { unsigned int w, h; };
unsigned int lis(struct Rectangle a[], unsigned int N)
{
// lis_counts stores the length of the LIS
// Mx stores maximum value
unsigned int lis_counts[N], Mx;
lis_counts[0] = 1;
for (int i = 1; i < N; i++)
{
Mx = 0;
// For each rectangles, check if it is a part of LIS
for (int j = 0; j < i; j++) if (a[i].w > a[j].w && a[i].h > a[j].h)
Mx = (Mx > lis_counts[j]) ? Mx : lis_counts[j];
lis_counts[i] = Mx + 1; // Update the length of LIS
}
Mx = 0;
for (int i = 0; i < N; i++) Mx = (Mx > lis_counts[i]) ? Mx : lis_counts[i];
return Mx;
}
int main()
{
unsigned int N, i;
scanf("%d", &N); // Read N inputs
if (0 > N || N > MAX_ITEMS) {
printf(0);
return 1;
}
struct Rectangle rects[N];
for (i = 0; i < N; i++){
scanf("%d", &rects[i].w); // Read width
scanf("%d", &rects[i].h); // Read height
}
printf("%d", lis(rects, N)); // Print LIS of rectangles
}