GYM 101606 D.Deranging Hat(水~)

Description

给出一个长度不超过 1000 的字符串 S ,假设将其升序排后形成的字符串为 T ,要求对 T 进行不超过 10000 次操作将其变成 S ,每次操作给出两整数 A , B ,如果 A 位置的字符不小于 B 位置的字符则交换两个位置的字符

Input

输入一个只由小写字母组成的串长不超过 1000 的字符串 S

Output

输出不超过 10000 次操作使得 T 可以变成 S

Sample Input

dude

Sample Output

4 3
3 2

Solution

S 快排,记录排序过程中需要交换的位置,之后逆序输出即可

Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=1005;
int n;
char a[maxn];
vector<P>ans;
void Solve(int l,int r)
{
    if(l>=r)return ;
    int i=l+1,j=r;
    char key=a[l];
    while(1)
    {
        while(i<=r&&a[i]<=key)i++;
        while(j>l&&a[j]>key)j--;
        if(i<j)swap(a[i],a[j]),ans.push_back(P(j,i));
        else break;
    }
    i--;
    if(i!=l)swap(a[i],a[l]),ans.push_back(P(i,l));
    Solve(l,i-1);
    Solve(i+1,r);
}
int main()
{
    scanf("%s",a+1);
    n=strlen(a+1);
    ans.clear();
    Solve(1,n);
    for(int i=ans.size()-1;i>=0;i--)
        printf("%d %d\n",ans[i].first,ans[i].second);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/v5zsq/article/details/80449867