蓝桥杯例题-快速分拣

1.题目

2.题解

2.1 使用unordered_map存储键值对,使用vector存储城市输入顺序

思路

主要是这里unordered_map无法保存顺序,map会自动排序,所以保存一手输入顺序
unordered_map<string, vector> mp; 这里的vector自动初始化创建一个空的vector了,后面可以直接使用.

代码

#include<bits/stdc++.h>
using namespace std;
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int n;
	cin >> n;
	unordered_map<string, vector<string>> mp;
	vector<string> citys;
	for (int i = 0; i < n; i++) {
		string id, city;
		cin >> id >> city;
		if(!mp.count(city)) {
			citys.push_back(city);
		}
		mp[city].push_back(id);
	}
	for(auto city : citys) {
		cout << city << " " << mp[city].size() << endl;
		for(auto str : mp[city]) {
			cout << str << endl;
		}
	}
	return 0;
}
posted @ 2024-04-09 01:34  DawnTraveler  阅读(31)  评论(0)    收藏  举报