PAT (Advanced Level) 1039 Course List for Student (字符串哈希)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w419387229/article/details/82053540

本来用map来映射名字的,但是超时了。由于名字只有四位,改用哈希。

顺便把数据结构字符串哈希那一部分翻出来重看了一遍。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
int n, k, cnt = 0;

struct Student{
	vector<int> q;
	int course_count = 0;
	Student(){}
	Student (int course, int count){
		q.push_back(course);
		course_count = count;
	}
}stu[180000];

int HashName(string name){
	return (name[0] - 'A') * 26 * 26 * 10 + (name[1] - 'A') * 26 * 10 + (name[2] - 'A') * 10 + (name[3] - '0');
}
int main(){
	scanf("%d%d",&n,&k);
	int cid, len;
	string name;
	for(int i = 0; i < k; ++i){
		scanf("%d%d",&cid,&len);
		for(int j = 0; j < len; ++j){
			cin >> name;
			stu[HashName(name)].q.push_back(cid);
			stu[HashName(name)].course_count++;
			
		} 
	}
	for(int i = 0; i < n; ++i){
		cin >> name;
		int index = HashName(name);
		cout << name << " " << stu[index].course_count;
		sort(stu[index].q.begin(),stu[index].q.end());
		for(int j = 0; j < stu[index].q.size(); ++j){
			printf(" %d",stu[index].q[j]);
		}
		cout << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/w419387229/article/details/82053540