UVa 11925:Generating Permutations(构造)

2 篇文章 0 订阅

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=845&page=show_problem&problem=3076

题意:输入一个1 ~ n (1n300) 的排列,用不超过 2n2 次操作把它变成升序。操作只有两种:交换前两个元素(操作1):把第一个元素移动到最后(操作2)。例如:输入排列为4,2,3,1,一个合法的操作序列为12122,具体操作是:4231->2431->4312->3412->4123->1234。(本段摘自《算法竞赛入门经典(第2版)》)。

关于题意以上表述有一些问题,题目要求的是从1,2,3,…,n的升序序列转化成题目所给的输入,其他的一样。

分析:
       从升序转换成输入的序列不好做,因此倒过来处理,其中把第一个元素放到最后这种操作改成把最后一个元素放到第一个就好了。最后的只要把结果倒着输出就可以了。

代码:

#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath>
#include <algorithm>
#include <set>
#include <string>

using namespace std;

const int maxn = 305;

int n, tmp;
int a[maxn];
string ans;

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

void change()
{
    tmp = a[n - 1];
    for (int i = n - 2; i >= 0; --i)
        a[i + 1] = a[i];
    a[0] = tmp;
}

int main()
{
    while (~scanf("%d", &n), n)
    {
        ans = "";
        for (int i = 0; i < n; ++i)
            scanf("%d", &a[i]);
        if (n == 1)
        {
            printf("\n");
            continue;
        }
        while (!judge())
        {
            if (a[0] > a[1] && a[0] != n)
            {
                swap(a[0], a[1]);
                ans += "1";
            }
            else
            {
                change();
                ans += "2";
            }
        }
        for (int i = ans.size() - 1; i >= 0; --i)
            printf("%c", ans[i]);
        printf("\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值