1375E - Inversion SwapSort - CodeForces Solution


constructive algorithms greedy sortings *2500

Please click on ads to support us..

C++ Code:

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
 
#define fi first
#define se second
#define DB double
#define U unsigned
#define P std::pair
#define LL long long
#define LD long double
#define pb emplace_back
#define MP std::make_pair
#define SZ(x) ((int)x.size())
#define all(x) x.begin(),x.end()
#define CLR(i,a) memset(i,a,sizeof(i))
#define FOR(i,a,b) for(int i = a;i <= b;++i)
#define ROF(i,a,b) for(int i = a;i >= b;--i)
#define DEBUG(x) std::cerr << #x << '=' << x << std::endl
 
const int MAXN = 1000+5;
int p[MAXN],q[MAXN],n,a[MAXN];
 
int main(){
    std::cin >> n;
    std::vector<std::pair<int,int>> S;

    for (int i = 1; i <= n; ++i) {
        scanf("%d",a+i);
        S.pb(a[i],i);
    }

    std::sort(all(S));
    FOR(i,1,n) {
        q[i] = S[i-1].se;
        p[q[i]] = i;
    }
    std::vector<P<int,int> > res;
    auto swap = [&](int x,int y){
        std::swap(q[p[x]],q[p[y]]);
        std::swap(p[x],p[y]);
        if(a[x] < a[y]) {
            std::swap(x,y);
        }
        res.pb(x,y);
    };
    ROF(i,n,1){
        int t = p[i];
        FOR(j,t+1,i) {
            swap(i,q[j]);
        }
    }
    printf("%d\n",SZ(res));
    for(auto x:res) {
        printf("%d %d\n",x.fi,x.se);
    }
 
    return 0;
}


Comments

Submit
0 Comments
More Questions

1607A - Linear Keyboard
EQUALCOIN Equal Coins
XOREQN Xor Equation
MAKEPAL Weird Palindrome Making
HILLSEQ Hill Sequence
MAXBRIDGE Maximise the bridges
WLDRPL Wildcard Replacement
1221. Split a String in Balanced Strings
1002. Find Common Characters
1602A - Two Subsequences
1555A - PizzaForces
1607B - Odd Grasshopper
1084A - The Fair Nut and Elevator
1440B - Sum of Medians
1032A - Kitchen Utensils
1501B - Napoleon Cake
1584B - Coloring Rectangles
1562B - Scenes From a Memory
1521A - Nastia and Nearly Good Numbers
208. Implement Trie
1605B - Reverse Sort
1607C - Minimum Extraction
1604B - XOR Specia-LIS-t
1606B - Update Files
1598B - Groups
1602B - Divine Array
1594B - Special Numbers
1614A - Divan and a Store
2085. Count Common Words With One Occurrence
2089. Find Target Indices After Sorting Array