2299 -- Ultra-QuickSort (poj.org)
#include<iostream>//归并排序 #include<cstring> using namespace std; typedef long long ll; const int N=500010; int a[N],tmp[N],ans; void merge_(ll l,ll mid,ll r){ int i=l,j=mid+1,t=0; while(i<=mid&&j<=r){ if(a[i]>a[j]){ tmp[t++]=a[j++]; ans+=mid-i+1; }else tmp[t++]=a[i++]; } while(i<=mid) tmp[t++]=a[i++]; while(j<=r) tmp[t++]=a[j++]; for(int i=0;i<t;i++) a[l+i]=tmp[i]; } void mergesort(ll l,ll r){ if(l<r){ ll mid=(l+r)>>1; mergesort(l,mid); mergesort(mid+1,r); merge_(l,mid,r); } } signed main(){ ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); int n; while(cin>>n && n!=0){ memset(a,0,sizeof(a)); ans=0; for(int i=0;i<n;i++) cin>>a[i]; mergesort(0,n-1); cout<<ans<<endl; } return 0; }
2388 -- Who's in the Middle (poj.org)
#include<iostream>//找中间数 using namespace std; const int N=10010; int data[N]; #define swap(a,b){int tmp=a;a=b;b=tmp;} int partition(int left,int right){ int i=left; int tmp=data[right]; for(int j=left;j<right;j++){ if(data[j]<tmp){ swap(data[j],data[i]); i++; } } swap(data[i],data[right]); return i; } void quicksort(int left,int right){ if(left<right){ int i=partition(left,right); partition(left,i-1); partition(i+1,right); } } signed main(){ ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); int n; cin>>n; for(int i=1;i<=n;i++) cin>>data[i]; quicksort(1,n); cout<<data[(n+1)/2]<<endl;; return 0; }
hdu账号莫名用不了,用洛谷的题平替一下,仅用修改一步,即可通过
P1908 逆序对 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
#include<iostream>//归并排序 #include<cstring> using namespace std; typedef long long ll; const int N=500010; ll a[N],tmp[N],ans; void merge_(ll l,ll mid,ll r){ ll i=l,j=mid+1,t=0; while(i<=mid&&j<=r){ if(a[i]>a[j]){ tmp[t++]=a[j++]; ans+=mid-i+1; }else tmp[t++]=a[i++]; } while(i<=mid) tmp[t++]=a[i++]; while(j<=r) tmp[t++]=a[j++]; for(int i=0;i<t;i++) a[l+i]=tmp[i]; } void mergesort(ll l,ll r){ if(l<r){ ll mid=(l+r)>>1; mergesort(l,mid); mergesort(mid+1,r); merge_(l,mid,r); } } signed main(){ ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); int n; cin>>n; memset(a,0,sizeof(a)); ans=0; for(int i=0;i<n;i++) cin>>a[i]; mergesort(0,n-1); cout<<ans<<endl; return 0; }
hdu账号早日回归希望!
标签:tmp,int,ll,基础,mid,++,ans,排序 From: https://www.cnblogs.com/accbulb/p/18013302