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