Let the required stack to be the sorted sequence, and the original stack to be the sequence to sort. A turtle is numbered by its position in the required stack: the top is 0, the second is 1, and so on. A turtle is said in reverse order if its number is less than the biggest number of the turtles above it in. Each time, find the turtle with the maximum number of all the turtles in reversed order, and let it climb up to the top.
In fact, all the turtles that have ever been in reverse order need to crawl out of the stack. Choose turtle with the maximum number would keep it from crawling out again.
Code:
- /*************************************************************************
- * Copyright (C) 2008 by liukaipeng *
- * liukaipeng at gmail dot com *
- *************************************************************************/
- /* @JUDGE_ID 00000 10152 C++ "ShellSort" */
- #include <algorithm>
- #include <cstdio>
- #include <cstring>
- #include <deque>
- #include <fstream>
- #include <iostream>
- #include <list>
- #include <map>
- #include <queue>
- #include <set>
- #include <stack>
- #include <string>
- #include <vector>
- using namespace std;
- int const namesize = 81;
- int const turtlecount = 200;
- struct strcomp
- {
- bool operator()(char const *s1, char const *s2)
- { return strcmp(s1, s2) < 0; }
- };
- int sort_turtles(int *turtles, int nturtles, int moves[])
- {
- int nmoves = 0;
- while (true) {
- int curm = -1;
- int revm = -1;
- int move = -1;
- for (int i = 0; i < nturtles; ++i) {
- if (turtles[i] > curm) {
- curm = turtles[i];
- } else if (turtles[i] < curm && turtles[i] > revm) {
- revm = turtles[i];
- move = i;
- }
- }
- if (revm < 0) break;
- for (int i = move; i > 0; --i) turtles[i] = turtles[i-1];
- turtles[0] = revm;
- moves[nmoves++] = revm;
- }
- return nmoves;
- }
- int main(int argc, char *argv[])
- {
- #ifndef ONLINE_JUDGE
- freopen((string(argv[0]) + ".in").c_str(), "r", stdin);
- freopen((string(argv[0]) + ".out").c_str(), "w", stdout);
- #endif
- int ncases;
- cin >> ncases;
- while (ncases-- > 0) {
- int nturtles;
- cin >> nturtles;
- cin.ignore(2048, '/n');
- char origin[turtlecount][namesize];
- for (int i = 0; i < nturtles; ++i) {
- cin.getline(origin[i], namesize);
- }
- char names[turtlecount][namesize];
- map<char *, int, strcomp> nameids;
- for (int i = 0; i < nturtles; ++i) {
- cin.getline(names[i], namesize);
- nameids.insert(make_pair(names[i], i));
- }
- int turtles[turtlecount];
- for (int i = 0; i < nturtles; ++i) {
- turtles[i] = nameids[origin[i]];
- }
- int moves[turtlecount];
- int nmoves = sort_turtles(turtles, nturtles, moves);
- for (int i = 0; i < nmoves; ++i) {
- cout << names[moves[i]] << '/n';
- }
- cout << '/n';
- }
- return 0;
- }
本文介绍了一种基于栈结构的龟排序算法,通过寻找逆序龟中编号最大的龟并将其移至顶部来实现排序。该算法确保所有逆序龟最终都会爬出栈外。
629





