UVA 120 - Stacks of Flapjacks
2015-06-15 23:11
375 查看
输入一行数字,代表从上到下的饼的编号,现可以对第k张饼以上的编号整体翻转。问要如何操作使饼的编号为非递减序列。
此题是Special Judge,答案不唯一。
我的思路就是用两个数组,一个数组存读入的顺序编号,另一个存排序后的编号。
然后从后往前处理,当a[i] 不等于 b[i]的时候,有两种操作方式:
1、a[0] 等于 b[i],这种直接执行整体翻转第k张饼以上的编号即可。
2、a[0] 不等于 b[i],这种需要找到等于b[i]的数字的位置x,然后整体翻转第x张饼以上的编号,然后a[0]位置就是b[i]编号了,然后再执行操作1即可。
代码里用到了C++读入数字的技巧:链接
此题是Special Judge,答案不唯一。
我的思路就是用两个数组,一个数组存读入的顺序编号,另一个存排序后的编号。
然后从后往前处理,当a[i] 不等于 b[i]的时候,有两种操作方式:
1、a[0] 等于 b[i],这种直接执行整体翻转第k张饼以上的编号即可。
2、a[0] 不等于 b[i],这种需要找到等于b[i]的数字的位置x,然后整体翻转第x张饼以上的编号,然后a[0]位置就是b[i]编号了,然后再执行操作1即可。
代码里用到了C++读入数字的技巧:链接
#include <stdio.h> #include <iostream> #include <sstream> #include <algorithm> using namespace std; int a[1005], b[1005], cnt; int find(int x) { for(int i = 0; i < cnt; i++) { if(a[i] == x) return i; } } int swp(int x, int y) { while(x < y) { swap(a[x], a[y]); x++; y--; } } int main() { string s; while(getline(cin, s)) { cnt = 0; stringstream ss(s); int x; while(ss >> x) { b[cnt] = x; a[cnt++] = x; } sort(b, b + cnt); for(int i = 0; i < cnt; i++) { printf(i?" %d":"%d", a[i]); } puts(""); for(int i = cnt - 1; i >= 0; i--) { if(a[i] != b[i]) { if(a[0] != b[i]) { int k = find(b[i]); printf("%d ", cnt - k); swp(0, k); } swp(0, i); printf("%d ", cnt - i); } } puts("0"); } return 0; }
相关文章推荐
- 《算法竞赛入门经典》解题索引
- 1.10055 - Hashmat the brave warrior
- 2.10071 - Back to High School Physics
- 3.458 - The Decoder
- 4.694 - The Collatz Sequence
- 6.494 - Kindergarten Counting Game
- 7.490 - Rotating Sentences
- 8.414 - Machined Surfaces
- 9.488 - Triangle Wave
- A.457 - Linear Cellular Automata
- B.489 - Hangman Judge
- C.445 - Marvelous Mazes
- 1.10494 - If We Were a Child Again
- 2.424 - Integer Inquiry
- 3.10250 - The Other Two Trees
- 5.465 - Overflow
- 6.113 - Power of Cryptography
- 7.10161 - Ant on a Chessboard
- 8.621 - Secret Research
- 9.401 - Palindromes