299 - Train Swapping

题意:
读入一串数字, 使用冒泡法从小到大进行排序, 计算需要的交换次数.

思路:
使用冒泡法, 每交换一次, 就递增1.

要点:
1. 使用 swap 交换两数.

题目:
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=98&page=show_problem&problem=235

代码:

# include <iostream>
# include <string>
# include <cstdio>
# include <cstring>
# include <vector>
# include <algorithm>
# include <cctype>
# include <iterator>
# include <assert.h>
using namespace std;

// swap 函数交换两数字

// 计算排序需要的交换次数
int main(int argc, char const *argv[])
{
  #ifndef ONLINE_JUDGE
    freopen("299_i.txt", "r", stdin);  
    freopen("299_o.txt", "w", stdout); 
  #endif
  
  int numCase = 0;
  cin >> numCase;

  while (numCase--) {
    int numCarrage;
    cin >> numCarrage;
    
    // 输入
    vector<int> carrages(numCarrage);
    for (int i=0; i<numCarrage; i++) {
      int carrageNO;
      cin >> carrageNO;
      carrages[i] = carrageNO;
    }

    // 冒泡排序, 由小到大
    int numSwap = 0;
    for (int i=0; i<numCarrage; i++) {
      for (int j=i; j<numCarrage; j++) {
        if (carrages[j] < carrages[i]) {
          swap(carrages[j], carrages[i]);
          ++numSwap;
        }
      }
    }

    printf("Optimal train swapping takes %d swaps.\n", numSwap);
  }
  return 0;
}

环境: C++ 4.5.3 - GNU C++ Compiler with options: -lm -lcrypt -O2 -pipe -DONLINE_JUDGE

你可能感兴趣的:(train,Swapping,299)