acm寒假训练1月27号第七题

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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值