题目链接:
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3076
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
int next[310];
int prev[310];
int head;
int tail;
int main()
{
int n;
while(scanf("%d", &n) && n != 0)
{
vector<int> my_array;
memset(next, -1, sizeof(next));
int x;
scanf("%d", &x);
head = x;
tail = x;
next[x] = -1;
prev[x] = -1;
for(int i = 2; i <= n; i++)
{
int y;
scanf("%d", &y);
next[x] = y;
prev[y] = x;
x = y;
}
tail = x;
if(n == 1)
printf("\n");
else
{
while(1)
{
int num1 = head;
int num2 = next[head];
if(num1 > num2 && !(num1 == n && num2 == 1))
{
if(next[num2] != -1)
prev[next[num2]] = num1;
next[num1] = next[num2];
next[num2] = num1;
prev[num2] = prev[num1];
prev[num1] = num2;
head = num2;
my_array.push_back(1);
}
int p = head;
/* while(p != -1)
{
printf("%d (next:%d,prev:%d), ", p, next[p], prev[p]);
p = next[p];
}
printf("\n");
*/ p = head;
while(next[p] != -1)
{
if(next[p] < p)
break;
p = next[p];
}
if(next[p] == -1)
break;
int last_num = tail;
int last_num2 = prev[tail];
next[last_num2] = next[last_num];
next[last_num] = head;
prev[head] = last_num;
prev[last_num] = -1;
head = last_num;
tail = last_num2;
my_array.push_back(2);
/* p = head;
while(p != -1)
{
printf("%d (next:%d,prev:%d), ", p, next[p], prev[p]);
p = next[p];
}
printf("\n");
*/ p = head;
while(next[p] != -1)
{
if(next[p] < p)
break;
p = next[p];
}
if(next[p] == -1)
break;
}
for(int i = my_array.size()-1; i >= 0; i--)
printf("%d", my_array[i]);
printf("\n");
}
}
return 0;
}
一道好题目,没有做出来。想到由乱序的情况按照规定的操作排成升序,但是没有思路。
后来看了别人解法发现,使用的是冒泡排序的想法,交换开头两个数相当于消灭相邻逆序对,然后把最后面的一个数移到最前面,相当于前进,再次检查新的数对。
冒泡排序的想法是消灭相邻逆序对。这点要考虑清楚。