Codeforces Round #598 (Div. 3)-B. Minimize the Permutation(1400思维+贪心+排序)

简介: 算法

B. Minimize the Permutation


飞机票

22.png

题意:

给你从1-n的全排列,每个位置有且只能进行一次置换,置换是当前位置和下一位置交换,求能得到的字典序最小的全排列是什么,输出它

思路:

贪心的去思考,既然要全排列最小,那么肯定是在能交换的情况下对数列中最小的数进行交换放在当前位置,又因为数据范围很小,于是我用flag标机当前位置,用map记录每个数的位置,暴力的去扫1-n中哪些数可以置换,置换条件就是当前数的位置比flag大,贪心的去完成就行

#include<bits/stdc++.h>
using namespace std;
const int maxn=105;
int a[maxn];
int main()
{
    int n,i,j,t,q;
    cin>>t;
    while(t--)
    {
        cin>>n;
        map<int,int>mo;
        for(i=1;i<=n;i++)
        {
            cin>>a[i];
            mo[a[i]]=i;
        }
        int flag=1;
        for(i=1;i<=n;i++)
        {
            if(mo[i]>flag)
            {
                for(j=mo[i];j>=flag+1;j--)
                {
                    a[j]=a[j-1];
                    mo[a[j]]=j;
                }
                a[flag]=i;
                int d2=mo[i];
                mo[i]=flag;
                flag=d2;
            }
            else if(mo[i]==flag)
            {
                flag++;
            }
        }
        for(i=1;i<=n;i++) cout<<a[i]<<" ";
        cn;
    }
    return 0;
}
相关文章
|
2天前
|
9月前
|
机器学习/深度学习 人工智能 BI
The Great Hero(Codeforces Round #700 (Div. 2))模拟+贪心思想和排序
The Great Hero(Codeforces Round #700 (Div. 2))模拟+贪心思想和排序
39 0
codeforces319——B. Psychos in a Line(思维+单调栈)
codeforces319——B. Psychos in a Line(思维+单调栈)
79 0
codeforces319——B. Psychos in a Line(思维+单调栈)
|
机器学习/深度学习 人工智能 BI
Codeforces Round #751 (Div. 2) D. Frog Traveler(bfs 优化)
Codeforces Round #751 (Div. 2) D. Frog Traveler(bfs 优化)
114 0
|
机器学习/深度学习
Codeforces1499——C. Minimum Grid Path(思维+分奇偶+贪心)
Codeforces1499——C. Minimum Grid Path(思维+分奇偶+贪心)
73 0
CodeForces - 1312D Count the Arrays(思维+组合数学)
CodeForces - 1312D Count the Arrays(思维+组合数学)
92 0
Codeforces Round #746 (Div. 2) C - Bakry and Partitioning(dfs 异或技巧 思维)
Codeforces Round #746 (Div. 2) C - Bakry and Partitioning(dfs 异或技巧 思维)
82 0
|
人工智能
AIM Tech Round 4 (Div. 2)(A,暴力,B,组合数,C,STL+排序)
A. Diversity time limit per test:1 second memory limit per test:256 megabytes input:standard input output:standard output ...
1126 0