My issue
i have trid solving this problem but i am not able to find bug in my approach
i am simply just adding the cyles length but i am not able to understandwhy do we need priority queue to store cyccles length and then add min cycles length first,adding in any order would give same answer
My code
#include <bits/stdc++.h>
using namespace std;
int dfs(vector < int > & v, vector < int > & vis, int st) {
int n = 0;
while (!vis[st]) {
vis[st] = 1;
st = v[st];
n++;
}
return n;
}
void ved() {
int n;
cin >> n;
vector < int > v(n + 1);
vector < int > vis(n + 1, 0);
for (int i = 1; i <= n; i++) {
cin >> v[i];
}
int c = 0;
int nk = 0;
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
int t=dfs(v, vis, i);
c+=t;
nk++;
}
}
if (nk == 1) {
cout << 0 << endl;
return;
}
cout << c << endl;
}
int main() {
// your code goes here
int t;
cin >> t;
while (t--) {
ved();
}
}
Problem Link: Costly Permutations Practice Coding Problem