Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 48111 | Accepted: 17549 |
Description
Input
Output
Sample Input
5 9 1 0 5 4 3 1 2 3 0
Sample Output
6 0 题意就是求所给序列的逆序数 可以用归并排序求#include <map> #include <list> #include <cmath> #include <queue> #include <stack> #include <string> #include <cstdio> #include <cstring> #include <cstdlib> #include <iostream> #include <algorithm> #define LL long long #define eps 1e-9 #define PI acos(-1.0) #define INF 0x3f3f3f3f #define CRR fclose(stdin) #define CWW fclose(stdout) #define WW freopen("output.txt","w",stdout) #define RR freopen("input.txt","r",stdin) using namespace std; const int MAX= 500100 ; int a[MAX]; int b[MAX]; int n; LL sum;//开始估计错值,用int 直接爆掉了 void Link_Sqrt(int low,int mid,int Low,int high) { int i=low,j=Low,s=0; while(i<=mid&&j<=high) { while(a[i]<=a[j]&&i<=mid&&j<=high) { b[s++]=a[i++]; } while(a[j]<a[i]&&i<=mid&&j<=high)//当a[i]>a[j]时,因为a[i--mid]与a[mid=1--high]都是有序序列,所以对与a[j]他的逆序数就是mid-i+1 { sum+=(mid-i+1); b[s++]=a[j++]; } } while(i<=mid) { b[s++]=a[i++]; } while(j<=high) { b[s++]=a[j++]; } for(int k=0;k<s;k++) { a[low+k]=b[k]; } } void Sqrt(int low,int high) { int i=low,j=high; if(i>=j) { return ; } int mid=(i+j)/2;//二分 Sqrt(i,mid); Sqrt(mid+1,j); Link_Sqrt(i,mid,mid+1,j);//归并 } int main() { while(scanf("%d",&n),n) { for(int i=0;i<n;i++) { scanf("%d",&a[i]); } sum=0; Sqrt(0,n-1); printf("%lld\n",sum); } return 0; }