【ACM】PAT. A1039 Course List for Student 【字符串hash & STL-set】

题目链接
题目分析
解题思路

思路(一):

map<string, set<int> > 边输入变保存

name用字符串hash转为int,进而用map<int, set<int> > ,同上

思路(二):

string用字符串hash转为int,作为数组set<int> cour[]的下标

**tips:**此处改用vector() + sort()也不会超时

注:需要把数组大小设为500000以上,作为全局变量放在main()外


map版本
/**************************
*@Author: 3stone
*@ACM: PAT-A1039
*@Time: 17/3/4
*@IDE: VS 2017
***************************/
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<map>
#include<set>
#include<string>
using namespace std;

map<string, set<int> > list;
int main() {
	int N, K, subID, num;
	char temp[5];
	string name;

	scanf("%d %d", &N, &K);
	for(int i = 1; i <= K; i++) {
		scanf("%d%d", &subID, &num);
		for(int j = 0; j < num; j++) {
			scanf("%s", temp);
			name = temp;

			list[name].insert(subID);
		}
	}

	for(int i = 0; i < N; i++) { //查询
		scanf("%s", temp);
		name = temp;
		printf("%s %d", temp, list[name].size());
		for(set<int>::iterator it = list[name].begin(); it != list[name].end(); it++) {
			printf(" %d", *it);
		}
		printf("\n");
	}

	system("pasue");

	return 0;
}
字符串hash 版本
/**************************
*@Author: 3stone
*@ACM: PAT-A1039
*@Time: 17/3/4
*@IDE: VS2017
***************************/
#include<cstdio>
#include<cstring> 
#include<algorithm>
#include<vector>
using namespace std;

const int N = 40010;
const int M = 26 * 26 * 26 * 10 + 1;

vector<int> cs[M];

int getID(char name[]){//字符串转数字ID 
	int id = 0;
	for(int i = 0; i < 3; i++){//前3位按26进制累加,最后1位数字直接加上去
		id = id * 26 + (name[i] - 'A'); 
	}
	id = id * 10 + (name[3] - '0');
	return id;
}

int main(){
	int n, k;
	while(scanf("%d%d", &n, &k) != EOF){
		char name[5];	
		for(int i = 0; i < k; i++){//输入数据 
			int x, course;
			scanf("%d%d", &course, &x);
			for(int j = 0; j < x; j++){
				scanf("%s", name);
				int id = getID(name);
				cs[id].push_back(course);
			}
		}
		//输入选课人员
		 for(int i = 0; i < n; i++){
			char name[5]; 
			scanf("%s", name);
			int id  = getID(name);
			
			sort(cs[id].begin(), cs[id].end());
			printf("%s %d", name, cs[id].size());
			for(int j = 0; j < cs[id].size(); j++)
				printf(" %d", cs[id][j]);
			printf("\n");
			
		 }//for-i
		
	} //while	
	return 0;
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值