Time limit1000 msMemory limit32768 kBOSWindowsSource
ZOJ Monthly, January 2003
problem description
The inversion number of a given number sequence a1, a2, …, an is the number of pairs (ai, aj) that satisfy i < j and ai > aj.
For a given sequence of numbers a1, a2, …, an, if we move the first m >= 0 numbers to the end of the seqence, we will obtain another sequence. There are totally n such sequences as the following:
a1, a2, …, an-1, an (where m = 0 - the initial seqence)
a2, a3, …, an, a1 (where m = 1)
a3, a4, …, an, a1, a2 (where m = 2)
…
an, a1, a2, …, an-1 (where m = n-1)
You are asked to write a program to find the minimum inversion number out of the above sequences.
问题链接:https://vjudge.net/contest/279648#problem/G
问题描述:输入n个数字,找出n个数字中反演数最小的数字并输出该反演数。
问题分析:
程序说明:
c++如下:
#include<cstdio>
#include<cstdlib>
#include<ctime>
#define LL long long
using namespace std;
struct SBT{
int l,r,dat,rnd,rep,son;
}tree[200010];
int n,treesize,root;
LL ans;
inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
inline void update(int k)
{
tree[k].son=tree[k].rep+tree[tree[k].l].son+tree[tree[k].r].son;
}
inline void right_rotate(int &k)
{
int t=tree[k].l;
tree[k].l=tree[t].r;
tree[t].r=k;
tree[t].son=tree[k].son;
update(k);
k=t;
}
inline void left_rotate(int &k)
{
int t=tree[k].r;
tree[k].r=tree[t].l;
tree[t].l=k;
tree[t].son=tree[k].son;
update(k);
k=t;
}
inline void insert(int &k,int x)
{
if(!k)
{
k=++treesize;
tree[k].dat=x;
tree[k].rep=1;
tree[k].son=1;
return;
}
tree[k].son++;
if (tree[k].dat==x)
{
tree[k].rep++;
return;
}
if(x<tree[k].dat)
{
insert(tree[k].l,x);
if(tree[tree[k].l].rnd>tree[k].rnd)right_rotate(k);
}else
{
insert(tree[k].r,x);
if(tree[tree[k].r].rnd>tree[k].rnd)left_rotate(k);
}
}
inline int query(int k,int x)
{
if (!k)return 0;
if (tree[k].dat>x)return tree[k].rep+tree[tree[k].r].son+query(tree[k].l,x);
if (tree[k].dat==x)return query(tree[k].r,x);
if (tree[k].dat<x)return query(tree[k].r,x);
}
int main()
{
n=read();
for (int i=1;i<=n;i++)
{
int x=read();
ans+=query(root,x);
insert(root,x);
}
printf("%lld\n",ans);
}