Codeforces 351B Jeff and Furik 概率 | DP

 

B. Jeff and Furik

time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Jeff has become friends with Furik. Now these two are going to play one quite amusing game.

At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.

Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.

You can consider that the coin shows the heads (or tails) with the probability of 50 percent.

Input

The first line contains integer n (1 ≤ n ≤ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the permutationp. The numbers are separated by spaces.

Output

In a single line print a single real value — the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.

Examples
input
2
1 2
output
0.000000
input
5
3 5 2 4 1
output
13.000000
Note

In the first test the sequence is already sorted, so the answer is 0.

 

题意:  两个人轮流游戏,先手交换相邻两个数,后手先抛硬币,正面,就随机找到一对相邻左大右小的数换,反面,就随机找到一对相邻右大左小的数换,直到整个数列升序排列,求最小期望步数。

思路:  由于第一个人每次都会减少一对逆序对,而后手会50%减少一对,50%增加一对,我们把两个人凑起来就是:

50%逆序对不变,50%减少2对

 

令dp[i]表示减少i个逆序对的步数的期望

dp[i]=dp[i]*0.5+dp[i-2]*0.5+2(要减少i个逆序对期望dp[i]步 = 此次两人共2步+减少dp[i-2]逆序对的期望步数+减少dp[i]逆序対的期望步数)

算出来就是dp[i]=dp[i-2]+4,初值:dp[0]=0,dp[1]=1

 

故dp数组分奇偶后就是两个等差数列,dp[i]=2*i(i为偶数),dp[i]=2*i-1(i为奇数),逆序对直接n^2暴力即可 

 

#include "bits/stdc++.h"
using namespace std;
#define rep(i, s, n) for(int i=s;i<n;i++)
const int N=3010;
int a[N];
int main() {
    int n;
    while(cin >> n){
        rep(i, 0, n) cin >> a[i];
        int s = 0;
        rep(i, 0, n) rep(j, i + 1, n) if (a[i] > a[j]) s++;
        double ans = s & 1 ? s / 2 * 4 + 1 : s * 2;
        printf("%.6f\n", ans);
    }
    return 0;
}

 

 

 

posted @ 2017-10-07 00:27  kimsimple  阅读(190)  评论(0编辑  收藏  举报