耗时一周。哭。
本题重在输入输出。所以对英文题目的理解非常重要。看清楚题目,省时省力。
题目要点:
1、开始有5×5的数据,每行仅有5个字符。注意:样例输入中的尾部空格是无法复制的(UVa官网上),其实是有的,所以不用考虑有多个空格或略过行尾空格直接换行的情况(我当时看样例输入行尾空格被略过直接换行,而大费周折)。
Each display line contains exactly 5 characters, beginning with the character on the leftmost square
2、动作指令仅有 A B L R 组成,可不用考虑其它非法字符,但是要考虑换行符。
The sequence of moves is represented by a sequence of As, Bs, Rs
3、动作指令可以出现多行,总以 0 结束。
This sequence of moves may be spread over several lines, but it always ends in the digit 0
4、输出格式有特殊要求:两个谜题puzzle中间用空行隔开。
Separate output from different puzzle records by one blank line.
简单清晰的AC代码可参考这里。以防该博客被删,我粘贴到下面。
顺便写个注解。
1、读取单个字符存储到 s[5][5] 中
2、判断首个字符 是否 'Z'
3、顺便找出 空格符
4、吞掉5*5数据每行末尾的 换行符
这样,5*5的数据就存储好了。
1、读取动作指令,进行移动(和拼图类似)
1.1、判断动作指令是否合规
1.2、空格和要移动的字符互换值
1.3、更新空格的坐标
2、吞掉结束标志字符 0
3、如果是首个puzzle,不输出\n(如果不是首个puzzle,则输出每两个puzzle的中间空行)
4、打印 Puzzle #1:
5、第一列字符,打印 字符,第二列到第五列,打印 字符+空格,最后每行补个 \n 换行符
下面是我从网上搜集的AC代码,不是我原创的,但是我觉得是思路比较清晰、比较符合直觉的一个。转自我的博客园。博客园不景气。
#include <cstdio>
#include <iostream>
using namespace std;
void Swap(char &s1,char &s2);
int main()
{
char ans,s[5][5];
int dx,dy,Case=0;//用于储存空格位置
while(true){
bool flag=true;
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
scanf("%c",&s[i][j]);
if(s[0][0]=='Z') return 0;
if(s[i][j]==' '){
dx=i; dy=j;
}
}
getchar();
}
while((ans=getchar())!='0'){
if(ans=='A'&&dx-1>=0){
Swap(s[dx][dy],s[dx-1][dy]);
dx-=1;
}
else if(ans=='B'&&dx+1<=4){
Swap(s[dx][dy],s[dx+1][dy]);
dx+=1;
}
else if(ans=='L'&&dy-1>=0){
Swap(s[dx][dy],s[dx][dy-1]);
dy-=1;
}
else if(ans=='R'&&dy+1<=4){
Swap(s[dx][dy],s[dx][dy+1]);
dy+=1;
}
else if(ans!='\n') flag=false;
}
getchar();
if(Case) printf("\n");
printf("Puzzle #%d:\n",++Case);
if(flag){
for(int i=0;i<5;i++){
for(int j=0;j<5;j++)
if(!j) printf("%c",s[i][j]);
else printf(" %c",s[i][j]);
printf("\n");
}
}
else
printf("This puzzle has no final configuration.\n");
}
return 0;
}
void Swap(char &s1,char &s2){
char c=s1;
s1=s2;
s2=c;
}