1039. Course List for Student

题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1039

考察查找

超时

// 超时的可能原因:
// 1. 使用了string
// 2. 暴力查找太低效
// 3. 大神分析,map本身为红黑树,查找效率并不高。
// 当想着优化查找的时候,大神哈希一步到位

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>


#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <algorithm>

using namespace std;

vector<string>course[2500+10];
vector<int> temp;

int N, K;
int id, NI;


void Input()
{
	scanf("%d%d", &N, &K);
	int i;
	for(i=1; i<=K; i++)
	{
		scanf("%d%d", &id, &NI);
		char name[10];
		while(NI-->0)
		{
			scanf("%s", name);
			string t=name;
			course[id].push_back(t);
		}
	}
}


void Query()
{

	char buf[10];
	string name;
	while(N-->0)
	{
		temp.clear();
		scanf("%s", buf);
		name = buf;
		
		int i;
		for(i=1; i<=K; i++)
		{
			//课程内查询,需要有序,才可折半查找
			int j;
			for(j=0; j<course[i].size(); j++)
			{
				if(name == course[i][j])
				{
					temp.push_back(i);
				}
			}// K个课程
		}

		// output
		printf("%s %d", name.c_str(), temp.size());
		int j;
		for(j=0; j<temp.size(); j++)
		{
			printf(" %d", temp[j]);
		}
		printf("\n");
	}

}

int main()
{
#ifdef ONLINE_JUDGE
#else
	freopen("E:\\in.txt", "r", stdin);
#endif

	Input();
	Query();
	return 0;
}

神曲

// ----------------------------------------------------------
// hash思想
// 具体源自那位神人已不知晓
//
// 为什么可以hash呢?
// 1. name长度固定,可确定hash公式
// 2. hash公式映射的唯一性
// 
// 这个公式怎么确定呢?字符看做是26进制。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;

vector <int> vt[300000];
int hassh(char *s){
	return 26 * 26 * 10 * (s[0] - 'A') + 26 * 10 * (s[1] - 'A') + 10 * (s[2] - 'A') + s[3] - '0';// AC
	//return 26 * 26 * 26 * (s[0] - 'A') + 26 * 26 * (s[1] - 'A') + 26 * (s[2] - 'A') + s[3] - '0';// 段错误
}

int n, k;
char s[10];
int main(){
	while(scanf("%d%d", &n, &k)!=EOF){
		for(int i = 0; i < k; i++){
			int index, b;
			scanf("%d%d", &index, &b);
			for(int j = 0; j < b; j++){
				scanf("%s", s);
				int t = hassh(s);
				vt[t].push_back(index);
			}
		}
		for(int i = 0; i < n; i++){
			scanf("%s", s);
			int t = hassh(s);
			printf("%s", s);
			sort(vt[t].begin(), vt[t].end());
			printf(" %d", vt[t].size());
			for(int j = 0; j < vt[t].size(); j++)
				printf(" %d", vt[t][j]);
			puts("");
		}
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值