【POJ 2503】Babelfish(字符串)
给定字典,再询问。
字典与询问之间有一个空行。
cin.peek()是一个指针指向当前字符。
#include<iostream> #include<string> #include<map> using namespace std; map<string, string>dic; string s, t; int f; int main() { ios::sync_with_stdio(false); while(cin >> s) if(cin.peek() == '\n')//指针当前指向\n if(!f) { f = 1; dic[s] = t;//当前读入的s是外星文,刚才读入的t是对应的英文 } else cout << ((t = dic[s]) != "" ? t : "eh" ) << "\n"; else//未换行说明s是字典的英文 { f = 0;//f=0代表下一个要读外星文 t = s; } }
处理空行的技巧
#include<cstdio> #include<algorithm> #include<cstring> using namespace std; #define N 100005 #define M 15 char s[N]; int c; struct mydic { char zh[M];//外星文 char en[M];//英文 } dic[N]; int cmp(const mydic &a, const mydic &b) { return strcmp(a.zh, b.zh) >= 0; } void solve() { int l = 0, r = c; while(l < r) { int m = r+l >> 1; int f = strcmp(s, dic[m].zh); if(f == 0) { printf("%s\n", dic[m].en); return; } if(f < 0) l = m + 1; else r = m; } printf("eh\n"); } int main() { while(gets(s)) { if(!s[0])break;//读到空行 sscanf(s,"%s%s",dic[c].en,dic[c].zh); c++; } sort(dic, dic + c, cmp); while(gets(s)) solve(); }
┆凉┆暖┆降┆等┆幸┆我┆我┆里┆将┆ ┆可┆有┆谦┆戮┆那┆ ┆大┆始┆ ┆然┆
┆薄┆一┆临┆你┆的┆还┆没┆ ┆来┆ ┆是┆来┆逊┆没┆些┆ ┆雁┆终┆ ┆而┆
┆ ┆暖┆ ┆如┆地┆站┆有┆ ┆也┆ ┆我┆ ┆的┆有┆精┆ ┆也┆没┆ ┆你┆
┆ ┆这┆ ┆试┆方┆在┆逃┆ ┆会┆ ┆在┆ ┆清┆来┆准┆ ┆没┆有┆ ┆没┆
┆ ┆生┆ ┆探┆ ┆最┆避┆ ┆在┆ ┆这┆ ┆晨┆ ┆的┆ ┆有┆来┆ ┆有┆
┆ ┆之┆ ┆般┆ ┆不┆ ┆ ┆这┆ ┆里┆ ┆没┆ ┆杀┆ ┆来┆ ┆ ┆来┆