主要思路就是求出序列的逆序数,此逆序数就是冒泡排序的交换次数
求逆序数采用归并排序,因为在每次归并排序中,如果左边大于右边,那么左边从此往后的数全部大于右边
code:
#include <set>
#include <map>
#include <ctime>
#include <queue>
#include <cmath>
#include <stack>
#include <limits>
#include <vector>
#include <bitset>
#include <string>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <string.h>
#include <iostream>
#include <algorithm>
#define ls rt<<1
#define rs rt<<1|1
#define Si set<int>
#define LL long long
#define pb push_back
#define PS printf(" ")
#define Vi vector<int>
#define LN printf("\n")
#define SD(a) scanf("%d",&a)
#define PD(a) printf("%d",a)
#define SET(a,b) memset(a,b,sizeof(a))
#define FF(i,a) for(int i(0);i<(a);i++)
#define FD(i,a) for(int i(a);i>=(1);i--)
#define FOR(i,a,b) for(int i(a);i<=(b);i++)
#define FOD(i,a,b) for(int i(a);i>=(b);i--)
#define readf freopen("input.txt","r",stdin)
#define writef freopen("output.txt","w",stdout)
const int maxn = 500001;
const int INF = 0x3fffffff;
const int dx[]={0,1,0,-1};
const int dy[]={1,0,-1,0};
const double pi = acos(-1.0);
using namespace std;
int sr[maxn],tr[maxn];
__int64 cnt;
void Merge(int r, int m, int t){
int k, j, i=r;
for (j =m+1, k = i; i<=m && j <= t; ++k){
if (sr[i] > sr[j]){
tr[k] = sr[j++];
cnt += m-i+1;
}
else
tr[k] = sr[i++];
}
while (i<=m)
tr[k++] = sr[i++];
while (j<=t)
tr[k++] = sr[j++];
for (i=r; i<=t; ++i)
sr[i] = tr[i];
}//Merge
void MSort(int r, int t){
int m = (r + t)/2;
if (r < t){
MSort(r, m);
MSort(m+1, t);
Merge(r, m, t);
}
}//MSort
int main(){
int n;
while (~scanf("%d", &n), n){
int i;
FOR(i,1,n) SD(sr[i]);
cnt = 0;
MSort(1,n);
printf("%I64d\n", cnt);
}
return 0;
}
分享到:
相关推荐
北大POJ2299-Ultra-QuickSort 解题报告+AC代码
POJ3211--Washing Clothes
POJ水题集-----50道左右-----增加自信啊..
POJ 1038--Bugs Integrated
POJ3036--Honeycomb Walk
POJ---1456.Supermarket测试数据及答案,题目描述:A supermarket has a set Prod of products on sale. It earns a profit px for each product x∈Prod sold by a deadline dx that is measured as an integral ...
北大POJ初级题-数据结构:解题报告+AC代码
POJ3259--Wormholes,使用bellman方法。
poj题目分类--acmer做题极有用资源
poj 1690 Your-Term-Project.md
poj 1240 Pre-Post-erous!.md
北大POJ3414-Pots 解题报告+AC代码
poj 2827 Auto-Calculation Machine.md
北大POJ3253-POJ3253-Fence Repair【STL优先队列】 解题报告+AC代码
北大POJ2002-Squares 解题报告+AC代码
用Java代码实现POJ(PKU)上题2494!
East Central North America 1999。50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50字50...
poj平台有关数据结构题的Java源码 1159 1276 2406 2502 2509 2513 2533 2778 3176
1390--blocks.rar
这是我个人写的POJ上2314题的Java实现,希望对喜欢ACM的人有帮助