poj2299解题报告(归并排序求逆序数)
来源:互联网 发布:网络规划设计师培训 编辑:程序博客网 时间:2024/05/18 03:18
POJ 2299,题目链接http://poj.org/problem?id=2299
题意:
给出长度为n的序列,每次只能交换相邻的两个元素,问至少要交换几次才使得该序列为递增序列。
思路:
其实就是求逆序数,那么直接向到的就是冒泡了,交换一次,记录一次即可。但是n的范围达到50W,冒泡O(n^2)的复杂度铁定超时。
然后、、、发现曾经微软有一道笔试题类似就是求逆序数的,对,没错,用归并。
例:合并两个序列(1,3,5)(2,4,6),新序列第二个元素是2,那么它和它前面的3、5形成了逆序数对,所以....
代码:
//3880K391MS#include <cstdio>#include <algorithm>int buf[500000];int ret[500000];unsigned long long count;void mergeArray(int *a, int first, int mid, int last, int *ret){int i = first, j = mid+1, k =0;int m = mid, n = last;while(i<=m && j<=n){if (a[i] <= a[j]) {ret[k++] = a[i++];}else {ret[k++] = a[j++];count += m-i+1; //记录}}while(i<=m) ret[k++] = a[i++];while(j<=n) ret[k++] = a[j++];for (int i=0;i<k; ++i) a[first+i] = ret[i];}void mergeSort(int data[], int first, int end, int *ret){if (first < end){int mid = (first + end)/2;mergeSort(data, first, mid, ret);mergeSort(data, mid+1, end, ret);mergeArray(data, first, mid, end, ret);}}int main(){int num;while (true){scanf("%d", &num);if (num <= 0) break;for (int i=0; i<num; ++i) scanf("%d", &buf[i]);count = 0;mergeSort(buf, 0, num-1, ret);printf("%lld\n", count);}return 0;}
0 0
- poj2299解题报告(归并排序求逆序数)
- POJ2299 归并排序求逆序数
- poj2299 归并排序求逆序数
- poj2299 归并排序求逆序数
- poj2299--归并排序求逆序数
- Ultra-QuickSort poj2299 (归并排序 求逆序数对)
- POJ2299 归并求逆序数
- POJ2299 Ultra-QuickSort 归并排序求逆序数对
- (归并排序求逆序数) poj2299 Ultra-QuickSort
- POJ2299-Ultra-QuickSort (归并排序求逆序数)
- POJ2299 Ultra-QuickSort (归并排序求逆序数模板)
- poj1804和poj2299归并排序求逆序数
- POJ2299 Ultra-QuickSort(归并排序,求逆序数)
- poj2299 归并排序求逆序对
- POJ2299(归并排序求逆序对)
- poj2299(求逆序对,归并排序)
- poj2299(归并排序求逆序对)
- Pku acm 2299 Ultra-QuickSort 排序算法解题报告(四)----归并排序(MegerSort)求逆序数
- Building a battery powered WiFi IoT Sensor with ESP8266, MS-5611 (GY-63), nodemcu and MQTT
- poj1068解题报告(模拟类)
- Struts2理解--动态方法和method属性及通配符_默认Action
- poj3080解题报告(暴力、最大公共子串)
- poj2388解题报告(排序)
- poj2299解题报告(归并排序求逆序数)
- cocos2d-x中使用sqlite
- cocos2d-x之jni使用(对接Android各种sdk)
- cocos2d-x, protobuf, no config.h, #error "No suitable threading library available."
- 浅谈多进程多线程的选择
- cocos2d-x使用ant打包
- 在onWindowFocusChanged方法中获取手机屏幕的高宽
- cocos2d-x使用ant批量打包
- cocos2d-x3.x使用rapidjson