a565簡單固定查表與哨兵終止

CPE:Language Detection (UVa 12250)

把有限的問候語與語言映射集中管理。

前往題目練習 →回報教學錯誤每筆時間 O(L),空間 O(1),L為問候語長度。

解題思路

六個已知字串各對應唯一語言,建立問候語到語言名稱的字典即可。對其他字串使用UNKNOWN,不需要用前綴、長度或字母相似程度推測,也不必轉換大小寫,輸入本來就是指定大寫。

讀到#先結束,不增加案例編號。其餘每讀一個問候語才把編號加1,按照Case k: LANGUAGE輸出。字典查不到時回傳預設值,避免無意插入空值而輸出空白。若EOF先出現,也自然結束。

Step-by-step animation

示意:HELLO、XYZ、HOLA、#

回報動畫錯誤
步驟 1 / 3

第一筆

HELLO在表內,輸出ENGLISH。

HELLO→ENGLISH
Case
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;

int main() {
    map<string, string> lang{{"HELLO", "ENGLISH"}, {"HOLA", "SPANISH"},
                             {"HALLO", "GERMAN"},  {"BONJOUR", "FRENCH"},
                             {"CIAO", "ITALIAN"},  {"ZDRAVSTVUJTE", "RUSSIAN"}};
    string s;
    int tc = 0;
    while (cin >> s && s != "#") {
        auto it = lang.find(s);
        cout << "Case " << ++tc << ": " << (it == lang.end() ? "UNKNOWN" : it->second) << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多