Submission #169955

#TimeUsernameProblemLanguageResultExecution timeMemory
169955AlexLuchianovSorting (IOI15_sorting)C++14
36 / 100
3 ms760 KiB
#include "sorting.h"
#include <iostream>
#include <vector>
#include <cassert>


int const nmax = 1000000;
int init[1 + nmax], n;
int v[1 + nmax], frec[1 + nmax], f[1 + nmax];
int xswap[1 + nmax], yswap[1 + nmax];
int pswap[1 + nmax], qswap[1 + nmax];

void solve(int pos, int &steps){
  if(pos == v[pos])
    return ;
  int oth = v[pos];
  pswap[steps] = pos;
  qswap[steps] = oth;
  std::swap(v[pos], v[oth]);
  frec[v[pos]] = pos;
  frec[v[oth]] = oth;
  steps++;
  solve(pos, steps);
}

bool tryit(int target){
  for(int i = 0; i < n; i++)
    v[i] = init[i];
  for(int i = 0; i < target; i++)
    std::swap(v[xswap[i]], v[yswap[i]]);
  for(int i = 0; i < n; i++)
    frec[v[i]] = i;
  for(int i = 0; i < n; i++)
    f[i] = i;

  int steps = 0;
  for(int i = 0; i < n; i++)
    solve(i, steps);

  if(target < steps)
    return false;

  while(steps < target) {
    pswap[steps] = qswap[steps] = 0;
    steps++;
  }

  for(int i = target - 1;0 <= i; i--){
    pswap[i] = f[pswap[i]];
    qswap[i] = f[qswap[i]];
    std::swap(f[xswap[i]], f[yswap[i]]);
  }

  for(int i = 0; i < n; i++)
    assert(i == v[i]);

  return true;
}

int binarysearch(int from, int to){
  if(from < to){
    int mid = (from + to) / 2;
    if(tryit(mid))
      return binarysearch(from, mid);
    else
      return binarysearch(mid + 1, to);
  } else
    return from;
}

int findSwapPairs(int N_, int S_[], int M, int X_[], int Y_[], int P[], int Q[]) {
  n = N_;
  for(int i = 0; i < n; i++)
    init[i] = S_[i];
  for(int i = 0; i < M; i++)
    xswap[i] = X_[i];
  for(int i = 0; i < M; i++)
    yswap[i] = Y_[i];
  int steps = binarysearch(0, M);
  tryit(steps);

  for(int i = 0; i < steps; i++)
    P[i] = pswap[i];
  for(int i = 0; i < steps; i++)
    Q[i] = qswap[i];

	return steps;
}


#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...