UVA 120 Stacks of Flapjacks 【构造法】

题目链接:https://cn.vjudge.net/problem/UVA-120

题意:

选择一个数k,从底部开始数第k个位置一直到顶部的饼反转过来,经过几次操作后,饼的直径是从底部到顶部以大到小排序的,输出每次操作的k值,0结尾为结束;

思路:

紫书说是用构造法,但题目A了,我也没懂啥是构造法;因为最后的结果是底部从大到小排序,我们可以优先找出最大直径的饼,优先压到底部,往后倒数第一的位置就可以不用考虑了,我们这里可以结合队列和栈来实现,从栈中取出k位置到顶部的数放到队列中,然后再从队列中依次取出放入栈中,就可以的得到反转后的数列;假设  21534  ,其中5最大,5对应的k值是3,那么就把k到顶部这部分反转过来,输出k = 3;得到 51234,因为找出最大值对应的k位置反转一次,这个最大值反转过后一定会在顶部,然后找到5应该放置的位置,再反转一次; 51234 对应的底部位置是倒数第一个,那么就输出1,然后1到顶部反转一次,得到 43215;这个5就放置好了,下次只需要考虑如何把4放到倒数第二个位置就行了,以此类推;

第一次WA:输入数据的时候,处理字符串转换为数字出现低级错误,一开始判断字符是否在0到9之间,然后再通过ascall转换;忘了这种方法只能处理一位数的转换;这里用ssstream的stringstream来实现,具体看代码,这个函数比sscanf还要慢,如果时间限制的紧的话就最好不要用;

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<sstream>

using namespace std;

#define IOS ios::sync_with_stdio(false); cin.tie(0);

typedef long long ll;
const int Maxn = 110;
const long long LINF = 1e18;
const int INF = 0x3f3f3f3f;

int a[Maxn],ss[Maxn],n;

bool cmp (const int &a1, const int &a2) {
    return a1 > a2;
}

bool input () {
    string s;
    getline(cin,s);
    if(s.size() == 0) return false;
    stringstream xx(s);
    n = 0;
    int x;
    while (xx >> x) a[++n] = x;
    cout << s << endl;
    return true;
}

int main (void)
{
    while (input()) {
        queue<int> qu;
        int head = 1, tail = 1,cnt = 1;
        for (int i = n; i >= 1; --i) {
            ss[tail] = a[i];
            tail++;
        }
        sort(a+1,a+n+1,cmp);
        int pos;
        while (cnt <= n) {
            if(ss[cnt] == a[cnt]) {
                cnt++; continue;
            }
            for (int i = cnt; i < tail; ++i) {
                if(ss[i] == a[cnt]) {
                        if(i != tail-1) cout << i << " ";
                        cout << cnt << " ";
                        pos = i; break;
                }
            }
            for (int i = tail-1; i >= pos; --i) qu.push(ss[i]);
            tail = pos;
            while (!qu.empty()) {
                int x = qu.front(); qu.pop();
                ss[tail] = x;
                tail++;
            }
            for (int i = tail-1; i >= cnt; --i) qu.push(ss[i]);
            tail = cnt;
            while (!qu.empty()) {
                int x = qu.front(); qu.pop();
                ss[tail] = x;
                tail++;
            }
            cnt++;
        }
        cout << "0" << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/godleaf/article/details/81638290
120