#include "sorting.h"
#include<bits/stdc++.h>
using namespace std;
int cnt_cycle(vector<int>& s, int n){
vector<bool> vis(n, false);
int cnt=0;
for(int v=0; v<n; v++){
if(vis[v]) continue;
cnt++;
vis[v]=true;
int mom=s[v];
while(mom!=v){
vis[mom]=true;
mom=s[mom];
}
}
return cnt;
}
int findSwapPairs(int n, int S[], int m, int x[], int y[], int p[], int q[]) {
//initialize
vector<int> s(n);
for(int i=0; i<n; i++){
s[i] = S[i];
}
//cnt minimal rounds
int rounds=-1;
int cnt = n-cnt_cycle(s, n);
for(int i=0; i<m; i++){
if(cnt<=i){
rounds = i;
break;
}
swap(s[x[i]], s[y[i]]);
cnt = n-cnt_cycle(s, n);
}
if(rounds==-1 && cnt<=m){
rounds=m;
}
assert(rounds!=-1);
//find swaps
vector<int> missing;
vector<int> next(n);
vector<bool> vis(n, false);
for(int v=0; v<n; v++){
if(vis[v]) continue;
int mom = v;
while(!vis[mom]){
vis[mom]=true;
missing.push_back(mom);
next[mom] = s[s[mom]];
mom=s[mom];
}
missing.pop_back(); //last in cycle doesn't need to be swapped anymore
}
vector<int> pos(n);
for(int i=0; i<n; i++){
pos[s[i]]=i;
}
for(int i=rounds-1; i>=0; i--){
if(missing.empty()){
p[i]=q[i]=0;
continue;
}
int a=missing.back(); missing.pop_back();
int b=next[a];
p[i] = pos[a];
q[i] = pos[b];
swap(pos[s[x[i]]], pos[s[y[i]]]);
swap(s[x[i]], s[y[i]]);
}
return rounds;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
300 KB |
Output is correct |
2 |
Correct |
1 ms |
212 KB |
Output is correct |
3 |
Incorrect |
1 ms |
296 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
300 KB |
Output is correct |
2 |
Correct |
1 ms |
212 KB |
Output is correct |
3 |
Incorrect |
1 ms |
296 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
212 KB |
Output is correct |
2 |
Incorrect |
1 ms |
340 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
300 KB |
Output is correct |
2 |
Correct |
1 ms |
212 KB |
Output is correct |
3 |
Incorrect |
1 ms |
296 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
11 ms |
408 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
11 ms |
408 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |