【OJ-UVa227】

耗时一周。哭。

本题重在输入输出。所以对英文题目的理解非常重要。看清楚题目,省时省力。

题目要点:

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 换行符

 1 #include <cstdio>
 2 #include <iostream>
 3 using namespace std;
 4 void Swap(char &s1,char &s2);
 5 
 6 int main()
 7 {
 8     char ans,s[5][5];
 9     int dx,dy,Case=0;//用于储存空格位置
10     while(true){
11       bool flag=true;
12       for(int i=0;i<5;i++){
13         for(int j=0;j<5;j++){
14           scanf("%c",&s[i][j]);
15           if(s[0][0]=='Z')  return 0;
16           if(s[i][j]==' '){
17             dx=i; dy=j;
18           }
19         }
20         getchar();
21       }
22       while((ans=getchar())!='0'){
23         if(ans=='A'&&dx-1>=0){
24             Swap(s[dx][dy],s[dx-1][dy]);
25             dx-=1;
26         }
27         else if(ans=='B'&&dx+1<=4){
28             Swap(s[dx][dy],s[dx+1][dy]);
29             dx+=1;
30         }
31         else if(ans=='L'&&dy-1>=0){
32             Swap(s[dx][dy],s[dx][dy-1]);
33             dy-=1;
34         }
35         else if(ans=='R'&&dy+1<=4){
36             Swap(s[dx][dy],s[dx][dy+1]);
37             dy+=1;
38         }
39         else if(ans!='\n') flag=false;
40       }
41       getchar();
42       if(Case)  printf("\n");
43       printf("Puzzle #%d:\n",++Case);
44       if(flag){
45         for(int i=0;i<5;i++){
46           for(int j=0;j<5;j++)
47             if(!j) printf("%c",s[i][j]);
48             else printf(" %c",s[i][j]);
49             printf("\n");
50         }
51       }
52       else
53         printf("This puzzle has no final configuration.\n");
54     }
55     return 0;
56 }
57 void Swap(char &s1,char &s2){
58     char c=s1;
59     s1=s2;
60     s2=c;
61 }

猜你喜欢

转载自www.cnblogs.com/muyun/p/10508136.html