题目:设计食物评分系统
思路:优先队列,堆
class FoodRatings {
public:
struct cmp{
bool operator()(const pair<int,string> &a,const pair<int,string> &b){
if(a.first==b.first){
return a.second>b.second;
}
return a.first<b.first;
}
};
unordered_map<string,string> mcui;
//食物名,烹饪方式
unordered_map<string,int> mrate;
//食物名,评分
unordered_map<string,priority_queue<pair<int,string>,vector<pair<int,string>>,cmp>> mem;
//烹饪方式,评分,食物名
FoodRatings(vector<string>& foods, vector<string>& cuisines, vector<int>& ratings) {
mcui.clear();
mrate.clear();
mem.clear();
int n=foods.size();
for(int i=0;i<n;i++){
mcui[foods[i]]=cuisines[i];
mrate[foods[i]]=ratings[i];
mem[cuisines[i]].push(make_pair(ratings[i],foods[i]));
}
//录入数据
}
void changeRating(string food, int newRating) {
mrate[food]=newRating;
mem[mcui[food]].push({newRating,food});
//可能会有重复的吴小数据,在highestRated中和mrate中数据进行对比验证
}
string highestRated(string cuisine) {
while(true){
pair<int,string> temp=mem[cuisine].top();
if(temp.first==mrate[temp.second]){
return temp.second;
}else{
mem[cuisine].pop();
}
}
}
};
/**
* Your FoodRatings object will be instantiated and called as such:
* FoodRatings* obj = new FoodRatings(foods, cuisines, ratings);
* obj->changeRating(food,newRating);
* string param_2 = obj->highestRated(cuisine);
*/