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 
#include 
#include 
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;
}

你可能感兴趣的:(Algorithm)