zoukankan      html  css  js  c++  java
  • 二分查找

    题目描述

    描述
    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 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 is the message translated to English, one word per line. Foreign words not in the dictionary should be translated as "eh".
    样例输入
    dog ogday
    cat atcay
    pig igpay
    froot ootfray
    loops oopslay

    atcay
    ittenkay
    oopslay
    样例输出
    cat
    eh
    loops
    提示
    Huge input and output,scanf and printf are recommended.
    来源
    Waterloo local 2001.09.22

    解题分析

    题目的意思就是查字典,但是由于字典的比较大,考虑使用二分查找。二分查找需要注意两点:1.查找过程中区间一致性,最初的查找区间是闭区间,子区间也要是闭区间,左闭右开也是类似的2.查找序列一定需要排好序。

    解题代码

    #include <iostream>
    #include <cstring>
    #include <algorithm>
    
    using namespace std;
    
    struct Entry{
        char en[11];
        char fr[11];
    }dict[100010];
    
    bool operator < (const Entry & a, const Entry & b){
        return (strcmp(a.fr, b.fr) < 0);
    }
    
    int main(){
        char word[11];
        int k = 0;
        while(true){
            scanf("%s%s", dict[k].en, dict[k].fr);
            k++;
            cin.get();
            if(cin.peek() == '
    ') break;
        }
        sort(dict, dict + k);
        while ((scanf("%s", word)) != EOF) {
            int l = 0, r = k - 1;
            int mid = l;
            while(l <= r){
                mid = l + (r - l)/2;
                int t = strcmp(word, dict[mid].fr);
                if( t == 0)
                {
                    printf("%s
    ", dict[mid].en);
                    break;
                }
                else if(t < 0)
                    r = mid - 1;
                else
                    l = mid + 1;
            }
            if(r < l)
                printf("eh
    ");
        }
        return 0;
    }
    
  • 相关阅读:
    POJ 3261 Milk Patterns (求可重叠的k次最长重复子串)
    UVaLive 5031 Graph and Queries (Treap)
    Uva 11996 Jewel Magic (Splay)
    HYSBZ
    POJ 3580 SuperMemo (Splay 区间更新、翻转、循环右移,插入,删除,查询)
    HDU 1890 Robotic Sort (Splay 区间翻转)
    【转】ACM中java的使用
    HDU 4267 A Simple Problem with Integers (树状数组)
    POJ 1195 Mobile phones (二维树状数组)
    HDU 4417 Super Mario (树状数组/线段树)
  • 原文地址:https://www.cnblogs.com/zhangyue123/p/12742461.html
Copyright © 2011-2022 走看看