//
// main.cpp
// uva 1611 - Crane
//
// Created by XD on 15/8/16.
// Copyright (c) 2015年 XD. All rights reserved.
//
/*
此题就是找到一种排序方法,使得序列升序最后打印出最终的操作序列。
这里只要找到一种方法就行。
这里采用了二分,逐步向目标位置靠近。
*/
#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include<vector>
#include <string.h>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <cstdio>
using namespace std ;
const int maxn = 10010 + 5 ;
const int doublemaxn = 16 * maxn ;
int pos[maxn] ;
int arr[maxn] ;
struct node{
int u ,v ;
node(int u ,int v):u(u),v(v){} ;
node(){} ;
};
int ans ;
node res[doublemaxn] ;
void reverse(int l , int r)
{
int temp ;int num = (r + l + 1)/2 ;
while (num <= r) {
temp = arr[num] ;
arr[num] = arr[l] ;
arr[l] = temp ;
pos[arr[l]] = l ;
pos[arr[num]] = num ;
l++ ;num++ ;
}
}
void Myswap(int i,int destination)
{
if (pos[i] == destination) {
return ;
}
if ((destination - pos[i] + 1)%2==0) {
res[ans].u = pos[i] ;res[ans++].v = destination ;
reverse(pos[i],destination) ;
Myswap(i, destination) ;
}
else{
res[ans].u = pos[i] ;res[ans++].v = destination -1;
reverse(pos[i],destination-1) ;
Myswap(i, destination-1) ;
res[ans].u = destination -1 ; res[ans++].v = destination ;
reverse(destination-1 ,destination) ;
}
}
int main(int argc, const char * argv[]) {
int T ,n;scanf("%d" ,&T) ;
while (T--) {
ans = 0 ;
scanf("%d" ,&n) ;
for (int i = 1; i <= n ;i++ ) {
scanf("%d" ,&arr[i]) ;
pos[arr[i]] = i ;
}
for (int i = n; i>0 ; i--) {
if (pos[i] == i) {
continue ;
}
Myswap(i, i) ;
}
printf("%d\n" ,ans) ;
if (ans ==0) {
continue ;
}
for (int i = 0; i < ans; i++) {
printf("%d %d\n" ,res[i].u ,res[i].v) ;
}
}
return 0;
}
uva 1611 - Crane
最新推荐文章于 2017-12-29 11:39:04 发布