Skip to content

Commit 65e0797

Browse files
authored
Create 1912. Design Movie Rental System (#891)
2 parents 39ef606 + 958ffd3 commit 65e0797

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

1912. Design Movie Rental System

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
struct unrentedComparator {
2+
bool operator()(const pair<int,int>& p1,const pair<int,int>& p2) const {
3+
if(p1.second==p2.second){
4+
return p1.first<p2.first;
5+
}
6+
return p1.second<p2.second;
7+
}
8+
};
9+
10+
struct rentedComparator {
11+
bool operator()(const tuple<int,int,int>& t1,const tuple<int,int,int>& t2) const {
12+
// tuple = {price, shop, movie}
13+
if(get<0>(t1)==get<0>(t2)){
14+
if(get<1>(t1)==get<1>(t2)){
15+
return get<2>(t1)<get<2>(t2);
16+
}
17+
return get<1>(t1)<get<1>(t2);
18+
}
19+
return get<0>(t1)<get<0>(t2);
20+
}
21+
};
22+
23+
class MovieRentingSystem {
24+
// movie -> set of {shop, price}, sorted by (price, shop)
25+
unordered_map<int,set<pair<int,int>,unrentedComparator>> unrentedMovie;
26+
27+
// rented movies = set of {price, shop, movie}
28+
set<tuple<int,int,int>,rentedComparator> rentedMovie;
29+
30+
unordered_map<string,int> priceMap; // "movie_shop" -> price
31+
32+
string getId(int movie,int shop){
33+
return to_string(movie)+"_"+to_string(shop);
34+
}
35+
36+
public:
37+
MovieRentingSystem(int n, vector<vector<int>>& entries) {
38+
for(auto &e: entries){
39+
int shop=e[0], movie=e[1], price=e[2];
40+
unrentedMovie[movie].insert({shop,price});
41+
string id=getId(movie,shop);
42+
priceMap[id]=price;
43+
}
44+
}
45+
46+
vector<int> search(int movie) {
47+
vector<int> shops;
48+
if(unrentedMovie.find(movie)==unrentedMovie.end()){
49+
return shops;
50+
}
51+
for(auto [shop,price]: unrentedMovie[movie]){
52+
shops.push_back(shop);
53+
if(shops.size()==5) break;
54+
}
55+
return shops;
56+
}
57+
58+
void rent(int shop, int movie) {
59+
int price=priceMap[getId(movie,shop)];
60+
unrentedMovie[movie].erase({shop,price});
61+
rentedMovie.insert({price,shop,movie});
62+
}
63+
64+
void drop(int shop, int movie) {
65+
int price=priceMap[getId(movie,shop)];
66+
rentedMovie.erase({price,shop,movie});
67+
unrentedMovie[movie].insert({shop,price});
68+
}
69+
70+
vector<vector<int>> report() {
71+
vector<vector<int>> reportResult;
72+
for(auto &[price,shop,movie]: rentedMovie){
73+
reportResult.push_back({shop,movie});
74+
if(reportResult.size()==5) break;
75+
}
76+
return reportResult;
77+
}
78+
};

0 commit comments

Comments
 (0)