# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
345677 | ogibogi2004 | Sorting (IOI15_sorting) | C++14 | 0 ms | 0 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "sorting.h"
static char _buffer[1024];
static int _currentChar = 0;
static int _charsNumber = 0;
static FILE *_inputFile, *_outputFile;
static inline int _read() {
if (_charsNumber < 0) {
exit(1);
}
if (!_charsNumber || _currentChar == _charsNumber) {
_charsNumber = (int)fread(_buffer, sizeof(_buffer[0]), sizeof(_buffer), _inputFile);
_currentChar = 0;
}
if (_charsNumber <= 0) {
return -1;
}
return _buffer[_currentChar++];
}
static inline int _readInt() {
int c, x, s;
c = _read();
while (c <= 32) c = _read();
x = 0;
s = 1;
if (c == '-') {
s = -1;
c = _read();
}
while (c > 32) {
x *= 10;
x += c - '0';
c = _read();
}
if (s < 0) x = -x;
return x;
}
#include "sorting.h"
#include <bits/stdc++.h>
using namespace std;
const int MAXN=2e5+6;
vector<pair<int,int> >swaps;
int seq[MAXN],seq1[MAXN],seq2[MAXN];
bool vis[MAXN];
int n;
vector<pair<int,int> >moves;
bool check(int x)
{
for(int i=0;i<n;i++)
{
seq1[i]=i;
}
for(int j=0;j<x&&j<swaps.size();j++)
{
swap(seq1[swaps[j].first],seq1[swaps[j].second]);
}
for(int i=0;i<n;i++)
{
seq2[i]=seq[seq1[i]];
}
int cnt=0;
memset(vis,0,sizeof(vis));
moves.clear();
/*cout<<x<<":";
for(int i=0;i<n;i++)
{
cout<<seq1[i]<<" ";
}
cout<<endl;*/
for(int i=0;i<n;i++)
{
if(vis[i]==0)
{
int u=i;
while(vis[u]==0)
{
vis[u]=1;
moves.push_back({i,seq2[u]});
u=seq2[u];
}
cnt++;
moves.pop_back();
}
}
//cout<<x<<" "<<cnt<<endl;
if(moves.size()<=x)
{
while(moves.size()<x)moves.push_back({0,0});
return 1;
}
else return 0;
}
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++)seq[i]=S[i];
for(int i=0;i<M;i++)swaps.push_back({X[i],Y[i]});
int low=0,high=M,mid,ans;
while(low<=high)
{
mid=(low+high)/2;
if(check(mid))
{
ans=mid;
high=mid-1;
}
else low=mid+1;
}
//cout<<ans<<endl;
check(ans);
for(int i=0;i<moves.size();i++)
{
P[i]=moves[i].first;Q[i]=moves[i].second;
}
return moves.size();
}
int main()
{
_inputFile = fopen("sorting.in", "rb");
_outputFile = fopen("sorting.out", "w");
int N, M;
N = _readInt();
int *S = (int*)malloc(sizeof(int) * (unsigned int)N);
for (int i = 0; i < N; ++i)
S[i] = _readInt();
M = _readInt();
int *X = (int*)malloc(sizeof(int) * (unsigned int)M), *Y = (int*)malloc(sizeof(int) * (unsigned int)M);
for (int i = 0; i < M; ++i) {
X[i] = _readInt();
Y[i] = _readInt();
}
int *P = (int*)malloc(sizeof(int) * (unsigned int)M), *Q = (int*)malloc(sizeof(int) * (unsigned int)M);
int ans = findSwapPairs(N, S, M, X, Y, P, Q);
fprintf(_outputFile, "%d\n", ans);
for (int i = 0; i < ans; ++i)
fprintf(_outputFile, "%d %d\n", P[i], Q[i]);
return 0;
}