Poj百练 2503: Babelfish (分类:二分)

一道简单字符串相关的二分题

题中有些OJ中常见的基础操作,下面是笔记:

cin.get() & cin.peek()

前者是观测并移除输入流的最后一个字符,类似出栈,经常用来舍弃回车等不需要的操作

后者是只用来获取输入流的最后一个字符

用例:当要求输入回车作为结尾,但输入内容中包含回车时

 

while(true): 无限循环  for(;;)一样

#include<cstring>
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;

struct Entry{
    char english[11];
    char foreign[11];
}entries[100005];

int Cmp(Entry entry1, Entry entry2 )
{
    return strcmp(entry1.foreign, entry2.foreign) < 0;
}

int main()
{
    int num = 0;
    char word[11];
    while(true){
        scanf("%s%s", entries[num].english, entries[num].foreign);
        num++;
        cin.get();      //去掉行尾的换行符
        if(cin.peek() == '\n')    //查看是否空行
            break;
    }

    sort(entries, entries+num, Cmp);//按照Cmp中的规则进行排序

    while(scanf("%s",word) != EOF)
    {
        int left = 0, right = num-1;
        int n = 0;
        //二分查找
        while( left <= right){
            int mid = left + (right-left)/2;
            n = strcmp(entries[mid].foreign, word);
            if(n < 0)
                left = mid+1;
            else if(n > 0)
                right = mid-1;
            else{
                printf("%s\n",entries[mid].english);
                break;
            }
        }
        if(n)
            printf("eh\n");
    }
    return 0;
}

 

猜你喜欢

转载自blog.csdn.net/a1097304791/article/details/81509411
今日推荐