二分贪心练习题-B2

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 ogday
cat atcay
pig igpay
froot ootfray
loops oopslay

atcay
ittenkay
oopslay

Sample Output

cat
eh

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值