uva 10152(线性表)

来源:互联网 发布:js禁止页面后退 编辑:程序博客网 时间:2024/06/05 15:19

题解:输入给出原始和目标两个列表,乌龟每次可以从最下面直接移动到最上面,要求用最少的移动次数让原始列表变为目标列表,输出按顺序移动的乌龟的名字。先把原始列表压栈,然后从下向上和目标列表对比位置,如果在同一位置就出栈,不在同一位置就存到另一个数组里然后也出栈,这样就得到了需要移动的乌龟的名字,然后在目标列表从下到上的和这写名字对比,目标列表内名字靠下的先输出,这样才能保证顺序。注意每次输出一组要输出空行。

#include <cstdio>#include <string>#include <iostream>#include <stack>using namespace std;const int N = 205;int main() {int t;scanf("%d", &t);while (t--) {int n;stack<string> s;string str2[N], temp[N], str1;scanf("%d", &n);getchar();for (int i = 0; i < n; i++) {getline(cin, str1);s.push(str1);}for (int i = 0; i < n; i++) {getline(cin, str2[i]);}int m = 0;for (int i = n - 1; i >= 0; i--) {if (s.top() != str2[i]) {temp[m++] = s.top();s.pop();i++;}elses.pop();if (s.empty())break;}for (int i = n - 1; i >= 0; i--)for (int j = 0; j < m; j++)if (temp[j] == str2[i]) {cout << temp[j] << endl;break;}printf("\n");}return 0;}


0 0
原创粉丝点击