题意:
给你几组字符串,前面是单词,后面是索引词,要求输入索引词便能输出单词!!!
思路:
首先考虑的是运用STL方面的知识来解决,但是你会发现TLE!又因为这是查找问题,所以使用二分查找!首先对单词进行排序,然后找到中间点,一层层往下推!
细节:
注意sscanf和printf的使用,可以提高程序效率!还要自己定义比较函数,
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <climits>
#include <algorithm>
#include <cmath>
#include <map>
using namespace std;
struct word {
char from[20],to[20];
} dic[100010];
bool cmp(const word &a,const word &b) {
if(strcmp(a.from,b.from) <= 0)
return true;
return false;
}
int bsearch(int lt,int rt,char *str) {
int mid;
while(lt <= rt) {
mid = (lt+rt)>>1;
if(strcmp(dic[mid].from,str) == 0) return mid;
if(strcmp(str,dic[mid].from) < 0) rt = mid-1;
else lt = mid+1;
}
return -1;
}
int main() {
int cnt = 0,i,ans;
char str[50];
while(gets(str) && str[0] != '\0') {
sscanf(str,"%s %s",dic[cnt].to,dic[cnt].from);
cnt++;
}
sort(dic,dic+cnt,cmp);
while(gets(str)) {
ans = bsearch(0,cnt,str);
if(ans == -1) puts("eh");
else printf("%s\n",dic[ans].to);
}
return 0;
}
心得:
一般查找问题,优先使用二分查找!