【习题 8-7 UVA

【链接】 我是链接,点我呀:)
【题意】

在这里输入题意

【题解】

让你把排列1..n变换成对应的输入序列。 每次可以交换前两个数字,或者把第一个数字放到末尾去。

可以逆向考虑。
即把无序的序列变换成有序的.
则第二种操作就变为"把末尾的数字放到最前面去"
则可以这样。
如果a[0]>a[1] 且a[0]不为n那么就swap(a[0],a[1])
否则把最后面的那个数字放到开头。
之所以加一个a[0]不为n的判断。是为了模拟那个冒泡排序的过程。
即到了最后一位的话,肯定就不用判断大小关系了
想一想冒泡排序->for (int i = 1;i < n;i++) if (a[i]>a[i+1]) swap(a[i],a[i+1]);
可以看到i也是不会到达n的。
我们这样把最后一个数字放到最前面。感觉就类似这个枚举的过程。

这个n就类似一个墙壁的功能。
把要排序的数字全都挡在它的“左边"

【代码】

#include <bits/stdc++.h>
using namespace std;

const int N = 3e2;

int n;
vector <int> a;
stack <int> sta;

bool ok(){
    for (int i = 0;i < n-1;i++) if (a[i]>a[i+1]) return false;
    return true;
}

int main(){
	#ifdef LOCAL_DEFINE
	    freopen("rush_in.txt", "r", stdin);
	#endif
	ios::sync_with_stdio(0),cin.tie(0);
    while (cin >>n && n){
        a.clear();
        for (int i = 0,x;i < n;i++) {
            cin >> x;
            a.push_back(x);
        }
        while (!ok()){
            if (a[0]>a[1] && a[0]!=n){
                swap(a[0],a[1]);
                sta.push(1);
            }else{
                sta.push(2);
                int temp = a.back();
                a.pop_back();
                a.insert(a.begin(),temp);
            }
        }
        while (!sta.empty()){
            cout<<sta.top();
            sta.pop();
        }
        cout << endl;
    }

	return 0;
}
原文地址:https://www.cnblogs.com/AWCXV/p/8243480.html