fork download
  1.  
  2. #include<stdio.h>
  3. int n,N,i,j,p,q,t,T,s,S,a[51];
  4. int main()
  5. {
  6. scanf("%d",&N); getchar();
  7. for(i=1;i<=N;i++)
  8. {
  9. S=s=0;
  10. scanf("%d",&n); getchar();
  11. for(j=1;j<=n;j++)
  12. {
  13. scanf("%d",&a[j]);
  14. } getchar(); a[n+1]='\0';
  15. for(j=1;j<=n-1;j++) /// searching a particular number from 1 to n-1
  16. {
  17. for(p=1;p<=n;p++) /// detecting numbers location
  18. {
  19. if(a[p]==j)
  20. {
  21.  
  22. T=a[p];
  23. for(q=p;q>=j;q--)
  24. {
  25. a[q]=a[q-1];
  26. }
  27. a[j]=T; s=p-j; /// p-j swaps is needed
  28. }
  29. //S=S+s;
  30. }
  31. S=S+s;
  32.  
  33. }
  34. printf("Optimal train swapping takes %d swaps.\n",S);
  35.  
  36. }
  37.  
  38. return 0;
  39. }
  40.  
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
Standard output is empty