N
代表測資數L
代表火車長度 (0 ≤ L ≤ 50)Optimal train swapping takes S swaps.
N
並用 while
迴圈重複,再讀每筆測資長度 L
並存入整數陣列中
int N;
int L;
int train[50] = {0};
scanf("%d", &N); //number of case
while(N--){
scanf("%d", &L); //length of train
for(i = 0; i < L; i++){
scanf("%d", &train[i]);
}
...
}
L
的範圍很小,所以用泡沫排序的概念計算交換次數即可 (一星題嘛 XD)
int count = 0;
for(i = 0; i < L - 1; i++){
for(j = 0; j < L - 1 - i; j++){
if(train[j] > train[j + 1]){
temp = train[j];
train[j] = train[j + 1];
train[j + 1] = temp;
count++;
}
}
}
printf("Optimal train swapping takes %d swaps.\n", count);
#include<stdio.h>
int main(){
int N;
int L;
int train[50] = {0};
int i, j;
int temp;
scanf("%d", &N); //number of case
while(N--){
scanf("%d", &L); //length of train
int count = 0;
for(i = 0; i < L; i++){
scanf("%d", &train[i]);
}
for(i = 0; i < L - 1; i++){
for(j = 0; j < L - 1 - i; j++){
if(train[j] > train[j + 1]){
temp = train[j];
train[j] = train[j + 1];
train[j + 1] = temp;
count++;
}
}
}
printf("Optimal train swapping takes %d swaps.\n", count);
}
return 0;
}