-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRussian_Doll_Envelopes.cpp
More file actions
78 lines (61 loc) · 1.87 KB
/
Russian_Doll_Envelopes.cpp
File metadata and controls
78 lines (61 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//https://leetcode.com/problems/russian-doll-envelopes/
#include <bits/stdc++.h>
#include <iostream>
#include <sstream>
#include <string>
#define maxn 5001
using namespace std;
pair<int, int> arr[maxn];
bool compele(vector<int> &s1, vector<int> &s2){
return (s1[0] > s2[0]) || ((s1[0]==s2[0]) && (s1[1]<=s2[1]));
}
vector<vector<int>> envelopes = {{5,4},{6,4},{6,7},{2,3}};
// return the last element index
int find_lowest_requirement(int index, int w, int h){
int left=0, right=index;
int i = (left+right)/2;
int flag = 0;
do{
if(arr[i].first > w && arr[i].second > h){
left = i;
flag = 0;
}else{
right = i;
flag = 1;
}
i = (left+right)/2;
}while(i != left);
if(flag){
if(arr[i].first > w && arr[i].second > h){
arr[i+1] = make_pair(w, h);
}else{
arr[i] = make_pair(w, h);
}
}else{// from the if statement i==right-1, replace the next item
if(arr[right].first > w && arr[right].second > h){
arr[right+1] = make_pair(w, h);
if(index < right+1) index = right+1;
//cout<<"right: "<<right<<" index: "<<index<< " w: "<<w<<" h: "<<h<<endl;
}else{
arr[i+1] = make_pair(w, h);
if(index < i+1) index = i+1;
}
}
return index;
}
int main() {
vector<vector<int>> tmp = envelopes;
sort(tmp.begin(), tmp.end(), compele);
vector<int> *ptr;
int sz = envelopes.size();
arr[0] = make_pair(tmp[0][0], tmp[0][1]);
int max_h = 0;
int index = 0;
for(int i=1;i<sz;i++){
ptr = &(tmp[i]);
index = find_lowest_requirement(index, (*ptr)[0], (*ptr)[1]);
//cout<<"index: "<<index<<endl;
}
cout<<index+1<<endl;
return 0;
}