二分贪心——B

xiaoxiao2021-02-27  112

题目要求:

输入最多包含100,000个字典条目,后跟一个空白行,后面最多可以有100,000个字。每个字典条目是包含英文单词的行,后跟一个空格和一个外语单词。字典中不会出现外来字不止一次。消息是外语中的一系列单词,每行一个单词。输入中的每个字都是最多10个小写字母的序列。

输出是将信息翻译成英文,每行一个字。不在字典中的外文应翻译为“eh”。

题目思路:定义结构数组分别保存词典的原意和翻译,对翻译进行排序,利用二分查找输入的单词。

细节处理:利用qsort进行快速排序,利用sscanf进行输入,分别保存原意和翻译,方便进行查找。

#include<iostream> #include<string> #include<stdio.h> #include<cstring> #include<algorithm> using namespace std; struct q { char b[20]; char c[20]; }q[100010]; int cmp(const void *a,const void *b) { return strcmp(q[*(int *)a].c,q[*(int *)b].c); } int main() { char a[25],d[25]; int n,t,h,k,l,m=0; int c[100010]; while(gets(a)) { sscanf(a,"%s %s",q[m].b,q[m].c); c[m]=m; l=strlen(q[m].b); if(l==0) break; m++; } qsort(c,m,sizeof(c[0]),cmp); while(gets(d)) { l=0; h=m-1; n=0; while(l<=h) { t=(l+h)/2; k=strcmp(q[c[t]].c,d); if(k>0) { h=t-1; } else if(k<0) { l=t+1; } else {n=1;break;} } if(n==1) printf("%s\n",q[c[t]].b); else printf("%s\n","eh"); } return 0; }

转载请注明原文地址: https://www.6miu.com/read-16916.html

最新回复(0)