学习归并排序时看了:https://blog.youkuaiyun.com/yuehailin/article/details/68961304,写的挺好的,推荐大家看下。
归并排序模板
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <set>
using namespace std;
typedef long long ll;
const ll mod=998244353;
const ll maxn=500005;
int A[maxn<<2];
void mergearray(int *a,int l,int r) {
int *temp=new int [r-l+1];
int mid=(l+r)>>1;
int i=l,j=mid+1,k=0;
while(i<=mid&&j<=r) {
temp[k++]=a[i]<=a[j]?a[i++]:a[j++];
}
while(i<=mid)temp[k++]=a[i++];
while(j<=r)temp[k++]=a[j++];
for(int c=0;c<k;c++)a[l+c]=temp[c];
}
void mergesort(int *a,int l,int r) {
if(l<r) {
int mid=(l+r)>>1;
mergesort(a,l,mid);
mergesort(a,mid+1,r);
mergearray(a,l,r);
}
}
void print(int n) {
for(int i=1;i<=n;i++)
cout<<A[i]<<" ";
cout<<endl;
}
int main () {
ios::sync_with_stdio(false);
int n;
cin>>n;
for(int i=1;i<=n;i++)cin>>A[i];
mergesort(A,1,n);
print(n);
return 0;
}
归并排序求逆序数(POJ 2299)
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <set>
using namespace std;
typedef long long ll;
const ll mod=998244353;
const ll maxn=500005;
int A[maxn<<2];
ll n,ans;
void mergearray(int *a,ll l,ll r) {
int *temp=new int [r-l+1];
int mid=(l+r)/2;
ll i=l,j=mid+1,k=0;
while(i<=mid&&j<=r) {
if(a[i]<=a[j])
temp[k++]=a[i++];
else {
temp[k++]=a[j++];
ans+=mid-i+1;
}
}
while(i<=mid)temp[k++]=a[i++];
while(j<=r)temp[k++]=a[j++];
for(ll c=0;c<k;c++)
a[l+c]=temp[c];
}
void mergesort(int *a,ll l,ll r) {
if(l<r) {
int mid=(l+r)/2;
mergesort(a,l,mid);
mergesort(a,mid+1,r);
mergearray(a,l,r);
}
}
void print(ll n) {
for(ll i=1;i<=n;i++)
cout<<A[i]<<" ";
cout<<endl;
}
int main () {
ios::sync_with_stdio(false);
while(cin>>n&&n) {
for(ll i=1;i<=n;i++)
cin>>A[i];
ans=0;
mergesort(A,1,n);
//print(n);
cout<<ans<<endl;
}
return 0;
}
975

被折叠的 条评论
为什么被折叠?



