二分贪心练习题-B2

来源:互联网 发布:php json null 处理 编辑:程序博客网 时间:2024/04/29 10:54
You have just moved from Waterloo to a big city. The people here speak an incomprehensible dialect of a foreign language. Fortunately, you have a dictionary to help you understand them.

Input

Input consists of up to 100,000 dictionary entries, followed by a blank line, followed by a message of up to 100,000 words. Each dictionary entry is a line containing an English word, followed by a space and a foreign language word. No foreign word appears more than once in the dictionary. The message is a sequence of words in the foreign language, one word on each line. Each word in the input is a sequence of at most 10 lowercase letters.

Output

Output is the message translated to English, one word per line. Foreign words not in the dictionary should be translated as "eh".

Sample Input

dog ogdaycat atcaypig igpayfroot ootfrayloops oopslayatcayittenkayoopslay

Sample Output

cateh

loops

本题题意,输入两列字符串,一列映射另一列进行查找,如果没这个字符串返回eh。这道题我先用map做的将超时了,后来才老老实实的用新学的二分法做。

细节:

1.strcmp()函数是比较两段字符串键值的函数 设这两个字符串为str1,str2,若str1==str2,则返回零;若str1>str2,则返回正数。若str1<str2,则返回负数。

2.sscanf()函数,这是我第一次接触此函数,%s表示以空格结束一次输入

3,get()以输入换行为结束输入,空格也可以输进去

思路:

因为之前map已经提交后超时了,故用二分法,先用结构题做好映射输入,以后一列字符串键值排序存好,然后按二分法套路beg,mid,end,循环找就是了。

#include <iostream>

#include <algorithm>

#include<stdio.h>

#include<vector>#include<string.h>#include<string>using namespace std;struct code{    char x[20],y[20];}a[100005];int cmp(code r,code s){    return strcmp(r.y,s.y)<0;//键值小的放前面}int main(){    int cnt=0;    char g[100],u[100];    while(gets(g))    {        if(g[0]=='\0') break;//如果没输入(即连续按两次回车键)结束输入        sscanf(g,"%s%s",a[cnt].x,a[cnt].y);        cnt++;    }    sort(a,a+cnt,cmp);    while(cin>>u)    {        int beg=0,end=cnt-1,mid,o=1;//o用来判断是否找到过        while(beg<=end)        {            mid=(beg+end)/2;            if(strcmp(u,a[mid].y)==0)            {                cout<<a[mid].x<<endl;                o=2;                break;            }            else if(strcmp(u,a[mid].y)<0)            {                end=mid-1;//因为上面是beg<=end所以用mid-1保证可以结束循环            }            else            {                beg=mid+1;            }        }        if(o==1){cout<<"eh"<<endl;}    }    return 0;}

0 0
原创粉丝点击