题目链接
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
int p , q, k =0;
char a[5][7];
while(gets(a[0])){
if(a[0][0] == 'Z') break;
for(int i = 1; i < 5; i++)
gets(a[i]);
for(int i = 0; i < 5; i++)
for(int j = 0; j < 5; j++)
if(a[i][j] == ' '){
p = i; q = j;break;
}
char c;
int t = 1, x = p, y = q;
while((c=getchar()) != '0') {
if(t == 1) {
switch(c) {
case 'A': x = p - 1;y = q;break;
case 'B': x = p + 1;y = q;break;
case 'L': x = p;y = q - 1;break;
case 'R': x = p;y = q + 1;break;
}
if(x < 0 || x > 4|| y < 0 || y > 4) {
t = 0;
}
else {
a[p][q] = a[x][y];
a[x][y] = ' ';
p = x; q = y;
}
}
}
getchar();
if(k) cout << "\n";
printf("Puzzle #%d:\n", ++k);
if(!t) cout << "This puzzle has no final configuration."<<"\n";
else {
for(int i = 0;i < 5; i++){
for(int j = 0;j < 5; j++)
printf(j==0 ? "%c" : " %c",a[i][j]);
cout << "\n";
}
}
}
return 0;
}
- 因为知道书上说gets函数存在漏洞,少用为好,所以我用了getline函数,并且理了下思路,再次写代码提交,虽然AC了,但是运行时间变成0.071s。把ff函数的内容去掉放到main里,运行时间是0.069s。用string定义确实会很慢,有兴趣的话可以试下vector等容器定义。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int tr[110];
int p, q, x, y, k = 0;
string a[5];
int check (int i) {
x = p + dir[i][0];
y = q + dir[i][1];
if (x < 0 || x > 4 || y < 0 || y > 4)
return 0;
return 1;
}
void ff() {
int t = 1;
char c;
while((c=getchar()) != '0') {
if( t && c != '\n') {
if( !check(tr[c]) ) t = 0;
else {
a[p][q] = a[x][y];
a[x][y] = ' ';
p = x; q = y;
}
}
}
if(k) printf("\n");
printf("Puzzle #%d:\n", ++k);
if(!t) printf("This puzzle has no final configuration.\n");
else {
for(int i = 0;i < 5; i++)
for(int j = 0;j < 5; j++)
printf(j!= 4 ? "%c " : "%c\n",a[i][j]);
}
}
int main()
{
tr['A'] = 0;
tr['B'] = 1;
tr['L'] = 2;
tr['R'] = 3;
while( getline(cin , a[0]) ){
if(a[0][0] == 'Z') break;
for(int i = 1; i < 5; i++) {
getline(cin , a[i]);
}
for(int i = 0; i < 5; i++)
for(int j = 0; j < 5; j++)
if( a[i][j] == ' ' ){
p = i; q = j; break;
}
x = p; y = q;
ff();
getchar();
}
return 0;
}