Submission #1213511

#TimeUsernameProblemLanguageResultExecution timeMemory
1213511LemserSorting (IOI15_sorting)C++20
54 / 100
30 ms328 KiB
#include "sorting.h"
#include <bits/stdc++.h>
using namespace std;
 
using ll = long long;
using ull = unsigned long long;
using lld = long double;
using ii = pair<int,int>;
using pll = pair<ll, ll>;
 
using vi = vector<int>;
using vll = vector<ll>;
using vii = vector<ii>;
using vpll = vector<pll>;
using vlld = vector<lld>;
 
#define all(x) x.begin(),x.end()
#define lsb(x) x&(-x)
#define gcd(a,b) __gcd(a,b)
#define sz(x) (int)x.size()
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define fls cout.flush()
 
#define fore(i, l, r) for (auto i = l; i < r; i++)
#define fo(i, n) fore (i, 0, n)
#define forex(i, r, l) for (auto i = r-1; i >= l; i--)
#define ffo(i, n) forex (i, n, 0)
 
bool cmin(ll &a, ll b) { if (b < a) { a=b; return 1; } return 0; }
bool cmax(ll &a, ll b) { if (b > a) { a=b; return 1; } return 0; }

void make_swap (ll i, ll j, vector<int> &a, vector<int> &pos) {
	swap(a[i], a[j]);
	swap(pos[a[i]], pos[a[j]]);
	// for (ll i: a) cout << i << ' ';
	// cout << '\n';
}

int findSwapPairs(int n, int A[], int M, int X[], int Y[], int P[], int Q[]) {
	vector<int> a(n), pos(n);
	fo (i, n) a[i] = A[i];
	fo (i, n) pos[a[i]] = i;
	if (is_sorted(all(a))) return 0ll;
	ll RM = M;
	auto b = a;
	fo (_, M) {
		swap(b[X[_]], b[Y[_]]);
		ll cnt = 0;
		vll vis(n, 0);
		fo (i, n) {
			if (b[i] == i || vis[i]) continue;
			ll j = b[i];
			vis[i] = 1;
			while (j != i) {
				j = b[j];
				vis[j] = 1;
				cnt += 1;
			}
		}
		if (cnt <= _+1) {
			RM = _ + 1;
			break;
		}
	}
	ll R = 0;
	make_swap (X[0], Y[0], a, pos);
	while (R < RM) {
		b = a;
		for (ll i = R+1; i < RM; i++) swap (b[X[i]], b[Y[i]]);
		if (is_sorted(all(b))) {
			P[R] = Q[R] = 0;
			R++;
			if (is_sorted(all(a))) return R;
			if (R < RM) make_swap (X[R], Y[R], a, pos);
			continue;
		}
		fo (i, n) {
			if (b[i] == i) continue;
			ll pos_a = pos[b[i]], pos_b = pos[i];
			P[R] = pos_a;
			Q[R] = pos_b;
			make_swap (pos_a, pos_b, a, pos);
			break;
		}
		R++;
		if (is_sorted(all(a))) return R;
		if (R < RM) make_swap (X[R], Y[R], a, pos);
	}
	return R;
}


#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...