# | 제출 시각 | 아이디 | 문제 | 언어 | 결과 | 실행 시간 | 메모리 |
---|---|---|---|---|---|---|---|
248998 | Evirir | 정렬하기 (IOI15_sorting) | C++17 | 0 ms | 0 KiB |
이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include "sorting.h"
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define watch(x) cout<<(#x)<<"="<<(x)<<'\n'
#define mset(d,val) memset(d,val,sizeof(d))
#define setp(x) cout<<fixed<<setprecision(x)
#define forn(i,a,b) for(int i=(a);i<(b);i++)
#define fore(i,a,b) for(int i=(a);i<=(b);i++)
#define pb push_back
#define F first
#define S second
#define pqueue priority_queue
#define fbo find_by_order
#define ook order_of_key
typedef long long ll;
typedef pair<ll,ll> ii;
typedef vector<ll> vi;
typedef vector<ii> vii;
typedef long double ld;
typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> pbds;
void amin(ll &a, ll b){ a=min(a,b); }
void amax(ll &a, ll b){ a=max(a,b); }
void YES(){cout<<"YES\n";} void NO(){cout<<"NO\n";}
void SD(int t=0){ cout<<"PASSED "<<t<<endl; }
const ll INF = ll(1e18);
const int MOD = 998244353;
const bool DEBUG = 1;
const int MAXN = 200005;
int findSwapPairs(int n, int A[], int m, int X[], int Y[], int P[], int Q[])
{
int ans=-1;
bool ok=1;
for(int i=0;i<n;i++){
if(A[i]!=i){ ok=0; break; }
}
if(ok) return 0;
for(int L=0,R=m-1;L<=R;)
{
int mid=(L+R)>>1;
//if(DEBUG){ cout<<"---------------------------\n"; watch(mid); }
int a[n], loc[n], floc[n];
vector<int> p,q;
for(int i=0;i<n;i++) a[i]=A[i], loc[a[i]]=i, floc[i]=i;
for(int i=mid;i>=0;i--){
int u=X[i], v=Y[i];
swap(floc[u],floc[v]);
}
int ptr=0;
for(int i=0;i<=mid;i++){
int u=X[i], v=Y[i];
swap(floc[u],floc[v]);
swap(loc[a[u]],loc[a[v]]);
swap(a[u],a[v]);
while(ptr<n && loc[ptr]==floc[ptr]) ptr++;
if(ptr==n){ p.pb(0); q.pb(0); }
else{
p.pb(loc[ptr]); q.pb(floc[ptr]);
//if(DEBUG){cout<<"Before:\n"; watch(ptr); watch(loc[ptr]); watch(floc[ptr]); forn(i,0,n) cout<<"loc["<<i<<"]="<<loc[i]<<'\n'; forn(i,0,n) cout<<a[i]<<" "; cout<<"\n\n"; }
swap(a[loc[ptr]], a[floc[ptr]]);
swap(loc[a[loc[ptr]]],loc[a[floc[ptr]]]);
//if(DEBUG){cout<<"After:\n"; watch(ptr); watch(loc[ptr]); watch(floc[ptr]); forn(i,0,n) cout<<"loc["<<i<<"]="<<loc[i]<<'\n'; forn(i,0,n) cout<<a[i]<<" "; cout<<"\n\n"; }
ptr++;
}
}
while(ptr<n && loc[ptr]==floc[ptr]) ptr++;
if(ptr==n){
//if(DEBUG) cout<<"PASSED\n";
ans=mid+1;
for(int i=0;i<=mid;i++) P[i]=p[i], Q[i]=q[i];
R=mid-1;
}
else L=mid+1;
}
return ans;
}
int main()
{
int N, M;
cin >> N;
int S[N];
for(int i = 0; i < N; ++i)
cin >> S[i];
cin >> M;
int X[M], Y[M];
for(int i = 0; i < M; ++i)
cin >> X[i] >> Y[i];
int P[M], Q[M];
int ans = findSwapPairs(N, S, M, X, Y, P, Q);
printf("%d\n", ans);
for (int i = 0; i < ans; ++i)
printf("%d %d\n", P[i], Q[i]);
return 0;
}