• UVa 11925 Generating Permutations (构造法)


    题意:给定一个序列,让你从一个升序列变成该序列,并且只有两种操作,操作1:交换前两个元素,操作2:把第一个元素移动到最后。

    析:一开始的时候吧,不会,还是看的题解,首先是要逆序来做,这样可能好做一点,那么操作1不变,操作2变成把最后一个元素放到最前面。

    就像是冒泡排序一样,如果第一个元素大于第二个,交换顺序,否则就把最后一个元素移动到最前面,但第三个样例就死循环了,我也算过,这样会一直重复某几个状态,

    所以我们要维护第一个值,如果是最大的元素,那么就不让他们交换了。

    代码如下:

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    #include <cstring>
    #include <vector>
    #include <iterator>
    
    using namespace std;
    const int maxn = 300 + 5;
    vector<int> ans, a;
    int n;
    
    bool judge(){
        for(int i = 0; i < n; ++i)
            if(a[i] != i+1)  return false;
        return true;
    }
    
    int main(){
        int x;
    //    freopen("in.txt", "r", stdin);
        while(scanf("%d", &n) == 1 && n){
            ans.clear();
            a.clear();
            for(int i = 0; i < n; ++i){ scanf("%d", &x);  a.push_back(x);  }
    
            if(1 == n){  puts("");  continue;  }
            while(true){
                if(judge())  break;
                if(a[0] > a[1] && a[0] != n){
                    swap(a[0], a[1]);
                    ans.push_back(1);
                }
                else{
                    a.insert(a.begin(), a[n-1]);
                    a.resize(n);
                    ans.push_back(2);
                }
            }
    
            for(int i = ans.size()-1; i >= 0; --i)
                printf("%d", ans[i]);
            printf("
    ");
        }
        return 0;
    }
    
  • 相关阅读:
    聪明人 & 普通人
    13种模型及方法论
    面向大规模商业系统的数据库设计和实践
    分治算法
    软件架构
    隐含前提思维模型
    Git回滚代码到某个commit
    使用arthas排查 test 问题
    Arthas
    docker 操作入门
  • 原文地址:https://www.cnblogs.com/dwtfukgv/p/5608349.html
Copyright © 2020-2023  润新知