校内测试-排序
题目
测试得分: 100
主要算法 : 模拟,排序(归并,冒泡)
题干:
归并排序求逆序对
代码
#include<stdio.h> #include<stdlib.h> #define LL long long #define FORa(i,s,e) for(LL i=s;i<=e;i++) #define FORs(i,s,e) for(LL i=s;i>=e;i--) #define File(name) freopen(name".in","r",stdin);freopen(name".out","w",stdout); using namespace std; inline LL read(); const LL N=200000; LL n,ans,a[N+1],b[N+1]; void sort(LL l,LL r) { if(l==r) return; LL mid=(l+r)/2,i=l,j=mid+1,k=l; sort(l,mid),sort(mid+1,r); while(i<=mid&&j<=r) { if(a[i]<=a[j]) b[k++]=a[i++]; else ans+=mid-i+1,b[k++]=a[j++]; } while(i<=mid) b[k++]=a[i++]; while(j<=r) b[k++]=a[j++]; FORa(i,l,r) a[i]=b[i]; } int main() { File("sort"); n=read(); FORa(i,1,n) a[i]=read(); sort(1,n); printf("%lld\n",ans); return 0; } inline LL read() { register char c=getchar();register LL f(1),x(0); while(c<'0'||c>'9') f=c=='-'?-1:1,c=getchar(); while(c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar(); return x*f; }