1455D - Sequence and Swaps - CodeForces Solution


dp greedy sortings *1600

Please click on ads to support us..

Python Code:


def solve():
    n, x = [int(x) for x in input().split()]
    a = [int(x) for x in input().split()]

    def isSorted():
        for i in range(n-1):
            if a[i] > a[i+1]: return False
        return True

    def getFirst():
        for i in range(n):
            if a[i] > x:
                return i
        return -1

    cnt = 0
    while not isSorted():
        idx = getFirst()
        if idx == -1:
            print(-1)
            return
        else:
            a[idx], x = x, a[idx]
            cnt += 1
        
    if not isSorted(): print(-1)
    else: print(cnt)

for _ in range(int(input())):
    solve()

C++ Code:

#include <bits/stdc++.h>
using namespace std;

typedef unsigned long long ull;
typedef long long ll;
typedef long double ld;

const ll mod  = 1e9+7;
const ld eps  = 1e-9 ;
const ll maxn = 1e5+1;
const ll inf  = 1e15 ;
const ll minf = -inf ;

#define mp make_pair
#define pb push_back
#define endl "\n"

bool check(vector<ll> &v)
{
    for(ll i=1 ; i<v.size() ; ++i)
    {
        if(v[i]<v[i-1]) return false;
    }
    return true;
}

bool solve()
{
    ll n,x;
    cin >> n >> x;
    vector<ll> v(n);

    for(ll i=0 ; i<n ; ++i) cin >> v[i];

    if(check(v))
    {
        cout << 0 << endl;
        return true;
    }

    for(ll i=0,cnt=0 ; i<n ; ++i)
    {
        if(v[i]>x)
        {
            swap(v[i],x);
            cnt++;
            if(check(v))
            {
                cout << cnt << endl;
                return true;
            }
        }
    }
    
    return false;    
}

int main()
{
    ios_base :: sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    #ifdef EPSILON
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
    freopen("error.txt","w",stderr);
    #endif

    ll t=1;
    cin >> t;

    while(t--)
    {
        if(solve()){}
        else
        
            cout << -1 << endl;
    }

    return 0;
} 


Comments

Submit
0 Comments
More Questions

455A - Boredom
1099A - Snowball
1651D - Nearest Excluded Points
599A - Patrick and Shopping
237A - Free Cash
1615B - And It's Non-Zero
1619E - MEX and Increments
34B - Sale
1436A - Reorder
1363C - Game On Leaves
1373C - Pluses and Minuses
1173B - Nauuo and Chess
318B - Strings of Power
1625A - Ancient Civilization
864A - Fair Game
1663B - Mike's Sequence
448A - Rewards
1622A - Construct a Rectangle
1620A - Equal or Not Equal
1517A - Sum of 2050
620A - Professor GukiZ's Robot
1342A - Road To Zero
1520A - Do Not Be Distracted
352A - Jeff and Digits
1327A - Sum of Odd Integers
1276A - As Simple as One and Two
812C - Sagheer and Nubian Market
272A - Dima and Friends
1352C - K-th Not Divisible by n
545C - Woodcutters