排序 + 二分:
Nested Dolls
Problem Description
Dilworth is the world’s most prominent collector of Russian nested dolls: he literally has thousands of them! You know, the wooden hollow dolls of different sizes of which the smallest doll is contained in the second smallest, and this doll is in turn contained in the next one and so forth. One day he wonders if there is another way of nesting them so he will end up with fewer nested dolls? After all, that would make his collection even more magnificent! He unpacks each nested doll and measures the width and height of each contained doll. A doll with width w1 and height h1 will fit in another doll of width w2 and height h2 if and only if w1 < w2 and h1 < h2. Can you help him calculate the smallest number of nested dolls possible to assemble from his massive list of measurements?
Input
On the first line of input is a single positive integer 1 <= t <= 20 specifying the number of test cases to follow. Each test case begins with a positive integer 1 <= m <= 20000 on a line of itself telling the number of dolls in the test case. Next follow 2m positive integers w1, h1,w2, h2, . . . ,wm, hm, where wi is the width and hi is the height of doll number i. 1 <= wi, hi <= 10000 for all i.
Output
For each test case there should be one line of output containing the minimum number of nested dolls possible.
Sample Input
4
3
20 30 40 50 30 40
4
20 30 10 10 30 20 40 50
3
10 30 20 20 30 10
4
10 10 20 30 40 50 39 51
Sample Output
1
2
3
2
代码:
#include<iostream> #include<algorithm> using namespace std; struct Doll //记录Doll的宽和高 { int w, h; bool operator<(Doll a) { if(w == a.w) return h > a.h; return w < a.w; } }; Doll doll[20001]; int p[20001]; int main() { int t, i, n, j, l, r, m, k; scanf("%d", &t); while(t --) { scanf("%d", &n); for(i = 0; i < n; i ++) //输入 scanf("%d %d", &doll[i].w, &doll[i].h); sort(doll, doll + n); //排序 m = 0; for(i = 0; i < n; i ++) { l = 0; r = m; while(l < r) //开始二分搜索 { k = (l + r)/2; if(p[k] >= doll[i].h) //在p[k]后面找 l = k + 1; else r = k; //在p[k]前面找 } p[l] = doll[i].h; //覆盖或者新增 m += (l == m); //如果没有找到,就新增一个 } printf("%d\n", m); } return 0; }