UVa 227 Puzzle
2015-08-07 21:38
267 查看
题目链接
这是一道简单模拟题,按题目要求操作即可。
因为知道书上说gets函数存在漏洞,少用为好,所以我用了getline函数,并且理了下思路,再次写代码提交,虽然AC了,但是运行时间变成0.071s。把ff函数的内容去掉放到main里,运行时间是0.069s。用string定义确实会很慢,有兴趣的话可以试下vector等容器定义。
这是一道简单模拟题,按题目要求操作即可。
[code]/*------------0.021s----------------*/ #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等容器定义。
[code]/*----------------0.071s-------------------*/ #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; }
相关文章推荐
- HDU 5294--Tricks Device【最小割 && 最短路处理,新建图】
- Windows Live Writer
- idea类似eclipse鼠标技巧java api信息
- 深度搜索DFS hdu-1312
- 【一些事晚报】大公司为什么爱“追杀”前高管
- 改进粒子系统-GPU实现
- 安卓环境的搭建(8.7)
- 文件读写操作
- HDU 1396 Counting Triangles
- Android ListView&异步加载的学习(四)——完善ListView滑动效率问题
- KMP算法详解
- Timer的使用
- python函数式编程
- Android(java)学习笔记144:Android音视频录制类MediaRecorder用法举例
- Linux下安装Eclipse及解决谷歌被墙无法更新SDK问题
- 再回首BS
- 利用JFrame实现JWindow的效果
- 13、C语言和设计模式(享元模式)
- centos 6.5 搭建ntp服务
- XML基础,与HTML的对比中学习