您的位置:首页 > 产品设计 > UI/UE

POJ 2299Ultra-QuickSort 逆序数,树状数组||并归排序

2016-06-02 16:02 267 查看
一道逆序数水题,随便复习一下并归排序,练习一下树状数组



第一个是闲的蛋疼用了输入外挂;

第二个是树状数组;

第三个是并归排序;

一般的时间,,有此可见输入外挂的强大,2333333

先给出树状数组的代码:

-

#include <stdio.h>
#include <iostream>
#include<algorithm>
#include <string.h>
using namespace std;
typedef long long LL;
#define N 500010
int tree
,n;
struct Node {
int val,pos;
} node
;
bool cmp(Node a,Node b) {
return a.val<b.val;//定义比较函数
}
int lowbit(int x) {
return x&-x;
}
void add(int x,int v) {
while(x<=n) {
tree[x]+=v;
x+=lowbit(x);
}
}
int Sum(int x) {
int tot=0;
while(x) {
tot+=tree[x];
x-=lowbit(x);
}
return tot;
}
int read() {   //输入外挂
int res=0,ch,flag=0;
if((ch=getchar())=='-')
flag=1;
else if(ch>='0'&&ch<='9')
res=ch-'0';
while((ch=getchar())>='0'&&ch<='9')
res=res*10+ch-'0';
return flag?-res:res;
}
int main() {
freopen("input.txt","r",stdin);
while(~scanf("%d",&n)) {
if(!n) break;
memset(tree,0,sizeof(tree));
for(int i=1; i<=n; i++) {
node[i].val=read();
node[i].pos=i;//离散化标记

}
sort(node+1,node+n+1,cmp);
LL sum=0;
for(int i=1; i<=n; i++) {
sum+=Sum(node[i].pos);
add(node[i].pos,1);
}
printf("%I64d\n",(LL)n*(n-1)/2-sum);//如果按我这么求sum是逆序数的补数(补数,,这个应该能理解吧的)

}
return 0;
}
并归的代码:

#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
typedef long long LL;
#define N 500010
//逆序数值存放在anti中
int a
,b
;
LL cnt;
void marge(int s,int m,int e)//归并排序的合并部分
{
int i=s,j=m+1,k=s;
while(i<=m&&j<=e)
{
if(a[i]<=a[j])
b[k++]=a[i++];
else
{
cnt+=j-k;
b[k++]=a[j++];
}
}
while(i<=m)
b[k++]=a[i++];
while(j<=e)
b[k++]=a[j++];
for(int i=s; i<=e; i++)
a[i]=b[i];
}
void mergesort(int s,int e)//归并排序
{
if(s<e)
{
int m=(s+e)/2;
mergesort(s,m);
mergesort(m+1,e);
marge(s,m,e);
}
}
int main()
{
int n;
//freopen("input.txt","r",stdin);
while(~scanf("%d",&n))
{
if(!n) break;
cnt=0;
for(int i=0; i<n; i++) scanf("%d",&a[i]);
mergesort(0,n-1);
printf("%I64d\n",cnt);

}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: