HDU 1394 线段树求逆序对

时间:2023-03-09 16:37:49
HDU 1394  线段树求逆序对

Minimum Inversion Number

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 25905    Accepted Submission(s): 15250

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.

Input
The input consists of a number of test cases. Each case consists of two lines: the first line contains a positive integer n (n <= 5000); the next line contains a permutation of the n integers from 0 to n-1.
Output
For each case, output the minimum inversion number on a single line.
Sample Input
10
1 3 6 9 0 8 5 7 4 2
Sample Output
16

题意:一个长度为n 的 0-n-1 的全排列  你可以进行若干次操作 把第一个数放到最后面 形成一个新的序列(最多n个)问所有序列中逆序对最少的数量。

解析:逆序对很好求 对于每一个数看它前面有多少个比它大的记为sum[ a[i] ] sigmasum[] 就是逆序的数量 每个位置都如此,线段树就是每次查询[a[i],n-1] 的个数;

假如当前序列的逆序对是ans 那么把当前第一个数a[i] 放到最后面 后面对于每个数[0,a[i]) sum[ ] 就会少一次 同样 sum[ a[i] ] = n-1-a[i]

所以 操作之后就是 ans+=n-a[i]+n-1-a[i]。取最大值就好了

#include <bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define all(a) (a).begin(), (a).end()
#define fillchar(a, x) memset(a, x, sizeof(a))
#define huan printf("\n")
#define debug(a,b) cout<<a<<" "<<b<<" "<<endl
#define ffread(a) fastIO::read(a)
using namespace std;
typedef long long ll;
const int maxn = 1e4+;
const int inf = 0x3f3f3f3f;
const int mod = ;
const double epx = 1e-;
const double pi = acos(-1.0);
//head-----------------------------------------------------------------
int sum[maxn*];
void PushUp(int rt)
{
sum[rt]=sum[rt<<]+sum[rt<<|];
}
void build(int l,int r,int rt)
{
if(l==r)
{
sum[rt]=;
return;
}
int mid=(l+r)>>;
build(l,mid,rt<<);
build(mid+,r,rt<<|);
PushUp(rt);
}
void update(int x,int val,int l,int r,int rt)
{
if(l==x&&r==x)
{
sum[rt]+=val;
return;
}
int mid=(l+r)>>;
if(x<=mid)
update(x,val,l,mid,rt<<);
else
update(x,val,mid+,r,rt<<|);
PushUp(rt);
}
int query(int L,int R,int l,int r,int rt)
{
if(L<=l&&R>=r)
{
return sum[rt];
}
int mid=(l+r)>>;
int ans=;
if(L<=mid)
ans+=query(L,R,l,mid,rt<<);
if(R>mid)
ans+=query(L,R,mid+,r,rt<<|);
return ans;
}
int a[maxn];
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
fillchar(sum,);
int ans=;
for(int i=;i<=n;i++)
{
scanf("%d",&a[i]);
update(a[i]+,,,n,); //出于方便从1开始
ans+=query(a[i]+,n,,n,);
}
int ret=inf;
for(int i=;i<=n;i++)
{
ans+=n-*a[i]-;
ret=min(ans,ret);
}
printf("%d\n",ret);
}
}

复习一下线段树基础。。