题意:
根据输入画出迷宫.输入的字符串中包含字符和数字, 其中数字表示其后紧跟着的字符的重复次数(若连续出现两个以上的数字, 则把这些数字相加起来作为重复次数), b 表示空格, ! 表示换行.
不同的输入使用空行进行分隔, 输出的迷宫也需要使用空行进行分隔.
思路:
逐个字符分析, 若是数字, 则相加; 否则, 进行输出.
要点:
1. 使用 atoi 将字符转化为整数, 或者使用 (int)('c' - '0');
2. 从此题开始引入 #ifndef...#endif 条件编译. 因为 UVa 的系统都是 define 了 ONLINE_JUDGE 的, 所以像以下代码一样写, 可以保证在本地编译时是从文件读取, 而在 UVa judge 系统是按 cin 进行读取的. 这样可以大大提高调试效率, 避免每次都要重新输入所有的 input.
#ifndef ONLINE_JUDGE
freopen ("445_i.txt", "r", stdin);
freopen ("445_o.txt", "w", stdout );
#endif
3. string 的 length() 和 size() 都同样返回字符串长度, 用 length() 是为了保持 C 的风格, 用 size() 则是为了保持 STL 的风格.
4. isdigit() 判断是否为数字. (<cctype>)
代码:
# include <iostream>
# include <cctype>
# include <cstdlib>
# include <string>
# include <cstdio>
using namespace std;
// 注意: atoi 转 char 为 int, <cstdlib>
// 可用 (int) (line[i] - '0') 来转化为整数
// 如果写成 while( !cin.eof() ) 就总是会报 wrong answer, 因为这样会多读入一个空行
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen ("445_i.txt", "r", stdin);
freopen ("445_o.txt", "w", stdout );
#endif
string line;
while( getline(cin, line) ){
int characterCount = 0;
for(int i=0; i<line.length(); i++){
if(isdigit(line[i])){
characterCount += line[i] - '0';
}else if(line[i] == '!'){
cout << endl;
}else{
for(int j=0; j<characterCount; j++){
cout << ('b' == line[i] ? ' ' : line[i]);
}
characterCount = 0;
}
}
cout << endl;
}
return 0;
}
环境:C++ 4.5.3 - GNU C++ Compiler with options: -lm -lcrypt -O2 -pipe -DONLINE_JUDGE