华为实习4.10机考第一题C++代码

华为2024.4.10机考第一题C++代码

第一题是一个关于字符串的模拟,但是对于C++来说,处理起来还是比较麻烦的。

难点就是在输入时各字符串是用逗号分割的。

#include<iostream>
#include<unordered_map>
#include<sstream>
#include<vector>
#include<algorithm>
using namespace std;

const int N = 1010;

typedef pair<string,string> PSS;

unordered_map<string, PSS> hashh;
unordered_map<string, int> hash1;
unordered_map<string, int> Factor;

int main(){
	int n , m;
	cin >> n ;
	string time[N], client[N], factor[N], init;
	int x[N];
	for(int i = 0 ; i < n ; i ++){
        // 这里若用getline,需要先把上面的换行符用getchar()读掉,不然会把换行符读入init
		cin >> init; 
		stringstream ss(init);
		getline(ss, time[i], ',');
		getline(ss, client[i], ',');
		getline(ss, factor[i], ',');
		ss >> x[i]; 
		if(x[i] < 0 || x[i] > 100) x[i] = 0;
	}
	cin >> m;
	for(int i = 0 ; i < m ; i ++){
		string s , factor1;
		int xx;
		cin >> s;
		stringstream ss(s);
		getline(ss, factor1, ',');
		ss >> xx;
		Factor[factor1] = xx; 
	}
	for(int i = 0 ; i < n ; i ++){
		if(hashh.find(client[i])!= hashh.end() && hashh[client[i]].first == time[i] && hashh[client[i]].second == factor[i]) continue;
		hashh[client[i]] = {time[i], factor[i]};
		hash1[client[i]] += x[i] * Factor[factor[i]];
	}
	vector<pair<string,int>> v;
	for(auto it: hash1){
		v.push_back({it.first,it.second});
	}
	sort(v.begin(),v.end());
	for(int i = 0 ; i < v.size(); i ++) cout << v[i].first << "," << v[i].second << endl;
	return 0;
	
}

测试样例:
输入:

5
162,client1,factorA,10
163,client2,factorB,15
164,client1,factorA,5
165,client1,factorB,10
166,client2,factorB,20
2
factorA,5
factorB,7

输出:

client1,145
client2,245

因为没有评测器,只过了测试样例,不确定是否能AC,希望各位大佬批评指正!

posted @ 2024-04-15 16:10  时光以北  阅读(40)  评论(0编辑  收藏  举报