模拟下冒泡,每次交换都+1即可。
#include <stdio.h> int main() { int n, l, s[55]; scanf("%d", &n); while (n--) { scanf("%d", &l); for (int i=0; i<l; i++) scanf("%d", &s[i]); int count = 0; for (int i=0; i<l-1; i++) // 模拟下冒泡 for (int j=1; j<l-i; j++) { if (s[j] < s[j-1]) { int tmp = s[j]; s[j] = s[j-1]; s[j-1] = tmp; count++; } } printf("Optimal train swapping takes %d swaps.\n", count); } return 0; }