华为4.6日笔试
一. 热词排序
- 注意点:
- 输入不定长字符串处理
- 多阶段的排序比较
- 不一定非得要用priority_queue,或者直接对map进行排序
- 可以考虑新建结构体,通过重写 sort 函数中的cmp函数完成多阶段的排序
// huawei Exam 4.6
struct HotWord
{
string word;
int cnt = 0;
int title_index = INT32_MAX;
int txt_index = INT32_MAX;
};
bool comp_hw_4_6_1(pair<string, HotWord>& p1, pair<string, HotWord>& p2){
HotWord a = p1.second;
HotWord b = p2.second;
if(a.cnt == b.cnt){
if(a.title_index == b.title_index){
return a.txt_index < b.txt_index;
}
else
return a.title_index < b.title_index;
}
else
return a.cnt > b.cnt;
}
void func1(){
int topN, M;
cin >> topN;
cin >> M;
unordered_map<string, HotWord> umap;
for (int i = 0; i < M; i++){
string temp1, temp2;
vector<string> title;
vector<string> text;
while(cin >> temp1){
title.push_back(temp1);
if (cin.get() == '\n') break;
}
while (cin >> temp2)
{
text.push_back(temp2);
if(cin.get() == '\n') break;
}
// title 第i个文章的title计数
for (int j = 0; j < title.size(); j++){
if(umap.count(title[j]) == 0)
umap[title[j]] = HotWord();
HotWord& hw = umap[title[j]];
hw.word = title[j];
hw.cnt += 3;
hw.title_index = min(hw.title_index, j);
}
// text 第i个文章的text计数
for (int j = 0; j < text.size(); j++){
if(umap.count(text[j]) == 0)
umap[text[j]] = HotWord();
HotWord& hw = umap[text[j]];
hw.word = text[j];
hw.cnt += 1;
hw.txt_index = min(hw.txt_index, j);
}
}
// sort操作
vector<pair<string, HotWord>> v(umap.begin(), umap.end());
sort(v.begin(), v.end(), comp_hw_4_6_1);
for (int i = 0; i < topN; i++){
cout << v[i].second.word << " ";
}
cout << endl;
return;
}
- 输入:
3 2
xinguan feiyan xinzeng bendi quezhen anli
ju baodao chengdu xinzeng xinguan feiyan bendi quezhen anli yili shenzhen xinzeng bendi quezhen anli liangli yi***gti kongzhi lianghao
xinguan yimiao linchuang shiyan
wuzhong xinguan yimiao tongguo sanqi linchaung shiyan xiaoguo lianghao
*输出:
xinguan xinzeng bendi