简单题(需要注意一个细节) 之 hdu 4847 Wow! Such Doge!
// [7/25/2014 Sjm]
/*
好几次 Runtime Error(ACCESS_VIOLATION)。。。后来发现:
当有符号数和无符号数出现在同一个表达式中,默认状态下(不做强制类型转换)表达式的值为将结果转化为无符号类型的值。
eg:
int as = 4;
string str = "abc";
cout << str.size() << endl; // 输出值为 3
cout << str.size() - as << endl; // 输出值非 -1
*/
1 // 法一: 2 #include <iostream> 3 #include <cstdlib> 4 #include <cstdio> 5 #include <string> 6 using namespace std; 7 string str, t_str; 8 string arr_str[17] = 9 { "doge", 10 "Doge", "dOge", "doGe", "dogE", 11 "DOge", "DoGe", "DogE", "dOGe", "dOgE", "doGE", 12 "DOGe", "DOgE", "DoGE", "dOGE", 13 "DOGE" 14 }; 15 16 void myGet(int pos) { 17 int lim = pos + 4; 18 t_str = ""; 19 for (int i = pos; i < lim; ++i) { 20 t_str += str[i]; 21 } 22 } 23 24 int main() 25 { 26 //freopen("input.txt", "r", stdin); 27 int ans = 0; 28 while (getline(cin, str)) { 29 if (str.size() < 4) continue; 30 // 加上此判断,防止Runtime Error,或者计算 (str.size() - 4) 时强制类型转换,即:(int)(str.size()) - 4 31 for (int i = 0; i <= (str.size() - 4); ++i) { 32 myGet(i); 33 for (int j = 0; j < 17; ++j) { 34 if (t_str == arr_str[j]) { 35 ans++; 36 break; 37 } 38 } 39 } 40 } 41 printf("%d\n", ans); 42 return 0; 43 }
1 // 法二: 2 #include <iostream> 3 #include <cstdlib> 4 #include <cstdio> 5 #include <string> 6 using namespace std; 7 string str, t_str; 8 9 int main() 10 { 11 //freopen("input.txt", "r", stdin); 12 int ans = 0; 13 while (getline(cin, str)) { 14 if (str.size() < 4) continue; 15 for (int i = 0; i <= (str.size() - 4); ++i) { 16 if ( 17 (str[i] == 'D' || str[i] == 'd') && 18 (str[i + 1] == 'O' || str[i + 1] == 'o') && 19 (str[i + 2] == 'G' || str[i + 2] == 'g') && 20 (str[i + 3] == 'E' || str[i + 3] == 'e')) { 21 ans++; 22 } 23 } 24 } 25 printf("%d\n", ans); 26 return 0; 27 }