ZOJ 4046 Good Permutation【容斥+逆序对】

A permutation of is called “good”, if and only if for all , at least one of the following condition is satisfied.

• and

Given a permutation of , each time you can choose two adjancent integers and swap them. How many swaps do you need at least to make the permutation a “good” one?

Input

There are multiple test cases. The first line of the input contains an integer , indicating the number of test cases. For each test case:

The first line contains an integer (), indicating the length of the permutation.

The second line contains integers (), indicating the given permutation.

It’s guaranteed that the sum of in all test cases will not exceed .

Output

For each test case output one line containing one integer, indicating the minimum number of swaps needed to make the permutation “good”.

Sample Input
2
5
3 5 4 2 1
1
1

Sample Output
2
0

Hint

For the first sample test case, we can change “3 5 4 2 1” to “3 4 5 2 1” first, then change it to “3 4 5 1 2” which is a good permutation.

Author: LIU, Rui

需要使得上面的序列变成两端严格单调+1递增的序列。
我们可以枚举所有出现的最终状态,并统计需要变换的次数。变换的次数可以通过求两次逆序对得到,并且先转移过去的数字与后转移过去的数字可能发生影响,注意考虑差值。

#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
const int maxn = 1e5 + 10;
typedef long long LL;
LL T, n, a[maxn], sum[maxn], pos[maxn];
LL ans1[maxn], mx[maxn];
LL low(LL x){return x&-x;}
void add(LL x){
    for(; x<=n; x+=low(x)) sum[x]++;
}
LL Sum(LL x){
    LL ans = 0;
    for(; x>0; x-=low(x)) ans += sum[x];
    return ans;
}
int main()
{
    scanf("%lld",&T);
    while(T--){
        scanf("%lld",&n);
        LL ans = 0;
        for(int i=1;i<=n;i++) sum[i] = 0;
        for(int i=1;i<=n;i++){
            scanf("%lld",&a[i]);
            pos[a[i]] = i;
            add(a[i]);
            LL less = Sum(a[i]);
            ans1[i] = i - less;// 前面比ai大的个数
            ans += ans1[i];
        }
        for(int i=1;i<=n;i++) sum[i] = 0;
        LL mi = ans, ans2 = 0;
        for(int i=1;i<=n;i++){
            ans -= ans1[pos[i]];
            ans2 = ans2 + n - pos[i] + i - 1;
            ans2 = ans2 - Sum(pos[i]) * 2;
            ans2 = ans2 - (i - Sum(pos[i]) - 1);
            add(pos[i]);
            mi = min(mi, ans + ans2);
        }
        printf("%lld\n",mi);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值