题意:
字典。从题中所给的映射中。给出key,然后找出对应的字符串,找不到则输出“eh”。
思路:
这题我是用二分做的,本来我是来学习哈希,还是二分来的比较简单= =
从小到大排序,然后对于每个询问,二分查找。复杂度O(nlogn)。
code:
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
typedef long long LL;
const int MAXN = 1e5+5;
struct PP {
char a[15], b[15];
bool operator < (const PP t) const {
int res = strcmp(a, t.a);
if(res < 0) return true;
return false;
}
}p[MAXN];
char str[30];
int cnt;
int find(char *s) {
int l = 0, r = cnt-1;
while(l <= r) {
int mid = (l+r)/2;
int res = strcmp(s, p[mid].a);
if(res == 0) return mid;
if(res < 0) r = mid-1;
else l = mid+1;
}
return -1;
}
int main() {
cnt = 0;
while(true) {
gets(str);
int len = strlen(str);
if(len == 0) break;
int idx = -1;
for(int i = 0;i < len; i++) {
if(str[i] == ' ') { idx = i; break;}
}
//
for(int i = 0;i < idx; i++)
p[cnt].b[i] = str[i];
p[cnt].a[idx] = '\0';
for(int i = idx+1;i < len; i++)
p[cnt].a[i-(idx+1)] = str[i];
p[cnt].b[len] = '\0';
cnt++;
}
sort(p, p+cnt);
/*
for(int i = 0;i < cnt; i++) {
cout<<p[i].a<<" "<<p[i].b<<endl;
}
*/
//
int tmp;
while(scanf("%s", str) != EOF) {
if((tmp = find(str)) != -1) printf("%s\n", p[tmp].b);
else puts("eh");
}
return 0;
}