一道冒泡排序的变形。
//299 - Train Swapping
#include <iostream>
#include <cstring>
using namespace std;
int train[60];
int bubble(int *, int);
int main()
{
freopen("data.txt", "r", stdin);
int cases;
scanf("%d", &cases);
while (cases--)
{
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++)
scanf("%d", &train[i]);
int steps = bubble(train, n);
printf("Optimal train swapping takes %d swaps.\n", steps);
}
return 0;
}
int bubble(int * a, int n)
{
int counts = 0;
for(int i = 1; i < n; i++)
{
int work = 1;
for(int j = 0; j < n - i; j++)
if(a[j] > a[j + 1])
{
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
work = 0;
counts++;
}
if(work)
break;
}
return counts;
}