华为4.6日笔试-热词排序

华为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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值