博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
集训第四周(高效算法设计)O题 (构造题)
阅读量:6868 次
发布时间:2019-06-26

本文共 2461 字,大约阅读时间需要 8 分钟。

A permutation on the integers from 1 to n is, simply put, a particular rearrangement of these integers. Your task is to generate a given permutation from the initial arrangement 1, 2, 3, . . . , n using only two simple operations.

•  Operation 1: You may swap the first two numbers. For example, this would change the arrangement 3,2,4,5,1 to 2,3,4,5,1.

• Operation 2: You may move the first number to the end of the arrangement. For example, this would change the arrangement 3,2,4,5,1 to 2,4,5,1,3.

Input

The input consists of a number of test cases. Each test case begins with a single integer n between 1 and 300. On the same line, a permutation of integers 1 through n is given where consecutive integers are separated by a single space. Input is terminated by a line containing ‘0’ which should not be processed.

Output

For each test case you are to output a string on a single line that describes a sequence of operations. The string itself should consist only of the characters ‘1’ and ‘2’. This string should be such that if we start with the initial arrangement 1, 2, 3, . . . , n − 1, n and successively apply rules 1 and 2 according to the order they appear in the output, then the resulting permutation is identical to the input permutation. The output string does not necessarily need to be the shortest such string, but it must be no longer than 2n 2 characters. If it is possible to generate the permutation using 0 operations, then you may simply output a blank line.

Sample Input

3 2 1 3

3 2 3 1

4 4 2 3 1

0

Sample Output

1

2

12122

 

题意:有一组序列,它原来初始排列为1 2 3 4 5。。。。n,经过操作1和操作2的可以变成输入中所给出的序列,要求输出经过了哪一些操作

如 123经过操作1可得213

思路:构造法。。。哪有算法可言,幸好题目说道不一定要求输入最少的那一系列操作,那么就为程序寻找一个进行操作1还是操作2的判定条件,条件是不能执行操作1就执行操作2,那么什么时候不能执行操作1呢,答案是前面两个数字有序时,无序时就交换呗,有序时你想换也换不了。。。重点在于这样的判断中有一个特殊情况,那就是如果前面两个数中有1时,那么无论他们有没有序,都不能执行操作1,否则会陷入循环,怎么也得不出结果了

其余的,模拟吧。。。

 

#include"iostream"#include"cstdio"#include"cstring" using namespace std; const int maxn=300+10; int a[maxn]; int n; string ans; void swap1() { int t; t=a[0]; a[0]=a[1]; a[1]=t; } void swap2() { int t; t=a[n-1]; for(int i=n-1;i>0;i--) {a[i]=a[i-1];} a[0]=t; } bool check() { for(int i=0;i
=0;i--) cout<
>n&&n) { memset(a,0,sizeof(a)); ans.clear(); for(int i=0;i
>a[i]; int T=2*n*n; while(T--) { if(check()) { print();break;} if(a[0]>a[1]&&a[0]!=1&&a[1]!=1) { swap1();ans+='1';} else { swap2();ans+='2';} } cout<

转载于:https://www.cnblogs.com/zsyacm666666/p/4707230.html

你可能感兴趣的文章
马拉车
查看>>
PHP计算中英混输字符串长度
查看>>
java有车有房有能力最基本运用
查看>>
js创建,获取,检测cookie
查看>>
子查询:相关子查询、无关子查询
查看>>
Python-使用Magellan进行数据匹配总结
查看>>
jersey rest webservice
查看>>
java 获取指定日前的前一天
查看>>
position
查看>>
ios内存管理(转)
查看>>
Unity 屏幕外死亡的敌人的分数显示在屏幕内
查看>>
整理网上的关于 路径遍历漏洞
查看>>
H5 离线缓存的用法
查看>>
我们为什么需要Windows Workflow Foundation?(摘)
查看>>
五笔打字学习
查看>>
vector
查看>>
printf("%d\n",printf("%d",printf("%d",i)));
查看>>
最小转弯问题
查看>>
Java线程(一)
查看>>
JQuery的几个小问题
查看>>