UVa 299 - Train Swapping

题目链接:UVa 299 - Train Swapping

题目没看懂。。。

看到了几个关键字,说是最多两个车厢交换,又看了看给的数据也合适冒泡排序交换次数,试了试。AC了。。

#include <iostream>

using namespace std;
const int MAX_N = 50 + 5;
int T,num,res,flag;
int arr[MAX_N];

int main()
{
    cin>>T;
    while(T--)
    {
        res = 0;
        cin>>num;
        for(int i = 0;i < num;i++)
            cin>>arr[i];

        for(int i = 0;i < num;i++)
        {
            flag = false;
            for(int j = 0;j < num - 1 - i;j++)
            {
                if(arr[j] > arr[j + 1])
                {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    res++;
                    flag = true;
                }
            }
            if(!flag)
                break;
        }
        cout<<"Optimal train swapping takes "<<res<<" swaps."<<endl;
    }
    return 0;
}


你可能感兴趣的:(UVa 299 - Train Swapping)