# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
405873 | jk410 | Sorting (IOI15_sorting) | C++17 | 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 <iostream>
#include <vector>
using namespace std;
int N,M;
int S[500],T[500],R[500];
bool Visited[500];
vector<pair<int,int>> SwapPair,Ans;
bool f(int k){
Ans.clear();
for (int i=0; i<N; i++){
T[i]=S[i];
Visited[i]=0;
}
for (int i=0; i<k; i++)
swap(T[SwapPair[i].first],T[SwapPair[i].second]);
for (int i=0; i<N; i++){
if (T[i]!=i&&!Visited[i]){
Visited[i]=true;
for (int j=T[i]; !Visited[j]; j=T[j]){
Visited[j]=true;
Ans.push_back({j,T[j]});
}
}
}
if (Ans.size()>k)
return false;
while (Ans.size()!=k)
Ans.push_back({0,0});
return true;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>N;
for (int i=0; i<N; i++){
cin>>S[i];
R[S[i]]=i;
}
cin>>M;
for (int j=0; j<M; j++){
int x,y;
cin>>x>>y;
SwapPair.push_back({x,y});
}
for (int i=0; i<=N; i++){
if (f(i))
break;
}
cout<<Ans.size();
for (int i=0; i<Ans.size(); i++){
swap(R[S[SwapPair[i].first]],R[S[SwapPair[i].second]]);
swap(S[SwapPair[i].first],S[SwapPair[i].second]);
cout<<"\n"<<R[Ans[i].first]<<" "<<R[Ans[i].second];
swap(S[R[Ans[i].first]],S[R[Ans[i].second]]);
swap(R[Ans[i].first],R[Ans[i].second]);
}
return 0;
}