题解:P13364 [GCJ 2011 Qualification] GoroSort

· · 题解

思路

首先每一次操作回到原位的数字的期望个数与原本的序列无关。

考虑如果我们拿 1\sim n 拍一次之后回到位置上的数的期望数。对于一个数,他回到位置上的期望显然为 \frac{(n - 1)!}{n!}。由于有 n 个数,所以最后得给这个数乘上一个 n,此时期望数为 \frac{(n - 1)!\times n}{n!} = 1。

延申一下,考虑我们现在有 m 个位置没有被摁住,参与打乱并且位置在这 m 个位置中的数的个数为 k。对于非这 k 个数的,他们回到位置上的期望显然为 0。对于这 k 个数,不难算出期望为 \frac{(m - 1)!}{m!},乘上一个 k 后变为 \frac{(m - 1)!\times k}{m!}。因为 k\le m,所以期望数 \frac{k}{m} \le 1。

因为每次操作回到原位的数的个数的期望小于等于 1,因此,我们操作次数期望的下界为不在原位的数的个数。考虑如何取到这个下界,此时我们肯定需要每次操作的所有位置都会同时操作这些位置最终的数字。我们发现,如果我们将回到原位的数全部摁住,每次就一定能满足这个条件,因此我们每次操作的期望回到原位的数的个数为 1,期望操作数为没有回到原位的数的个数。

代码

#include<bits/stdc++.h>
using namespace std;
int t, n, ans;
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    cin >> t;
    for(int tt = 1; tt <= t; tt ++){
        cin >> n;
        ans = 0;
        for(int i = 1; i <= n; i ++){
            int x;
            cin >> x;
            if(x != i){
                ans ++;
            }
        }
        cout << "Case #" << tt << ": " << ans << ".000000\n"; 
    }
    return 0;
}