fork(3) download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. int n,k;
  7. cin>>n;
  8. int temp,temp2;
  9. string s="";
  10. int lol;
  11. for(temp=0;temp<n;temp++)
  12. {
  13. cin>>lol;
  14. s+=char(lol+48);
  15. }
  16. cin>>k;
  17. string target=s;
  18. sort(target.begin(),target.end());
  19. //cout<<target<<"\n";
  20. queue<pair<string,int>> q;
  21. q.push(make_pair(s,0));
  22. map<string,bool> visited;
  23. while(!q.empty())
  24. {
  25. string st=q.front().first;
  26. int cnt=q.front().second;
  27. q.pop();
  28. if(visited[st]) continue;
  29. visited[st]=true;
  30. if(st==target)
  31. {
  32. cout<<cnt<<"\n";
  33. return 0;
  34. }
  35. cnt++;
  36. for(temp=0;temp<=n-k;temp++)
  37. {
  38. string sst=st;
  39. int troll=0;
  40. for(temp2=temp;temp2<temp+k;temp2++)
  41. {
  42. sst[temp2]=st[temp+k-troll-1];
  43. troll++;
  44. }
  45. //cout<<sst<<" "<<cnt<<"\n";
  46. q.push(make_pair(sst,cnt));
  47. }
  48. }
  49. cout<<-1<<"\n";
  50. }
Success #stdin #stdout 0s 3424KB
stdin
5
5 4 1 2 3
3
stdout
3