题目链接: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;
}