# | 제출 시각 | 아이디 | 문제 | 언어 | 결과 | 실행 시간 | 메모리 |
---|---|---|---|---|---|---|---|
405873 | jk410 | Sorting (IOI15_sorting) | C++17 | 0 ms | 0 KiB |
이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#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;
}