uva 1611 - Crane

//
//  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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值