The first week match's mistake-2

2023-05-26,,

旋转排列

(https://www.luogu.com.cn/problem/B3688)

解读一下题目:

要求从给定的数组拿出最后一个数字后

看看变化后的数组的最后一个数字是否是要求的数字

想到用栈和队

再看看例子

1.发现如果给的数组的最后一位刚好是所要求的得重新去排

2.排过一次后达到目的数字了就只输出一次

注意更新栈的栈顶就可以了还有防止越界了

我就是因为没有注意只有一个数的情况re了

上代码

queue<int> q1,q2;
stack<int> st2;
for (int i = 1; i <= n; i++) {
int a; cin >> a;
q1.push(a),st2.push(a);
}
if(n == 1)cout << q1.front();
else {
for (int ii = 1; ii <= n; ii++) {
int t = st2.top();
st2.pop();
if (st2.top() == n) {
q2.push(t);
for (int i = 1; i <= n - 1; i++) {
q2.push(q1.front());
q1.pop();
}
for (int i = 1; i <= n; i++) {
if (i == n)cout << q2.front();
else {
cout << q2.front() << ' ';
q2.pop();
}
}
break;
} else {
for (int i = 1; i <= n; i++) {
if (st2.empty())break;
else st2.pop();
}
q2.push(t);
for (int i = 1; i <= n - 1; i++) {
q2.push(q1.front());
q1.pop();
}
q1.pop();
for (int i = 1; i <= n; i++) {
if (i == n) {
cout << q2.front() << endl;
q1.push(q2.front()), st2.push(q2.front());
q2.pop();
} else {
cout << q2.front() << ' ';
q1.push(q2.front()), st2.push(q2.front());
q2.pop();
}
}
}
}
}

把一个队换成数组好像更号,不用pop那么多次

The first week match's mistake-2的相关教程结束。

《The first week match's mistake-2.doc》

下载本文的Word格式文档,以方便收藏与打印。