1 solutions

  • 0
    @ 2026-8-21 9:26:39

    消失的逆序:题解

    题解与参考实现

    设当前排列长度为 mm,逆序数为 II。只要 m≥2m\ge2,游戏就一定还能继续:若排列不是递增的,则至少存在一对相邻逆序,可以执行交换;若排列递增,由于它包含且仅包含 1,2,…,m1,2,\ldots,m,它只能是 [1,2,…,m][1,2,\ldots,m],此时可以执行删除。因此游戏恰好在排列长度变为 00 或 11 时结束。

    下面考察两种操作对逆序数奇偶性的影响。交换一对相邻逆序只会改变这一对元素之间的大小关系,因此逆序数恰好减少 11,奇偶性翻转。

    删除操作删去的是相邻的 x,x+1x,x+1。任取另一个元素 zz,它同时位于这两个元素的左侧或右侧。又因为不存在满足 x<z<x+1x<z<x+1 的整数,所以 zz 与 x,x+1x,x+1 形成的逆序数只能是 00 或 22;而 x,x+1x,x+1 自身不构成逆序。因此删除操作删去偶数个逆序,重新编号又不会改变剩余元素之间的相对大小,故逆序数的奇偶性不变。

    定义

    Φ=I+⌊m2⌋(mod2).\Phi=I+\left\lfloor\frac m2\right\rfloor\pmod2.

    交换操作使 II 的奇偶性翻转而 mm 不变;删除操作不改变 II 的奇偶性,但使 mm 减少 22,从而使 ⌊m/2⌋\lfloor m/2\rfloor 减少 11。所以每次合法操作都会使 Φ\Phi 翻转。

    终止状态的长度为 00 或 11,此时 I=0I=0 且 ⌊m/2⌋=0\lfloor m/2\rfloor=0,所以 Φ=0\Phi=0。因此整局游戏的操作次数奇偶性恰好等于初始状态的 Φ\Phi。若初始 Φ=1\Phi=1,Alice 执行最后一步并获胜;否则 Bob 获胜。由此得到

    $$\text{Alice 获胜} \iff I+\left\lfloor\frac n2\right\rfloor\equiv1\pmod2.$$

    只需计算逆序数的奇偶性。将排列看成置换 i↦aii\mapsto a_i,设其环数为 cc。一个长度为 kk 的环可以分解成 k−1k-1 次交换,所以置换的奇偶性为

    n−c(mod2).n-c\pmod2.

    排列的置换奇偶性也等于逆序数的奇偶性,故

    I≡n−c(mod2).I\equiv n-c\pmod2.

    最终判断

    n−c+⌊n2⌋n-c+\left\lfloor\frac n2\right\rfloor

    是否为奇数即可。遍历置换的所有环,时间复杂度为 O(n)O(n),空间复杂度为 O(n)O(n)。

    #include<bits/stdc++.h>
    #define ll long long
    #define ld long double
    #define maxn 200005
    #define rep(i,x,y)  for(int i=(x);i<(y);i++)
    #define YES cout<<"YES"<<'\n';return;
    #define NO cout<<"NO"<<'\n';return;
    #define Yes cout<<"Yes"<<'\n';return;
    #define No cout<<"No"<<'\n';return;
    #define fi first
    #define se second
    #define eb emplace_back
    #define pb push_back
    #define all(a)  a.begin(),a.end()
    using namespace std;
    inline ll read() {
        ll x = 0,f = 1;
        char ch=getchar();
        while(ch<'0'||ch>'9'){
            if(ch=='-')f=-1;
            ch=getchar();
        }
        while(ch>='0'&&ch<='9'){
            x=(x << 1)+(x << 3)+(ch^48);
            ch=getchar();
        }
        return x*f;
    }
    void solve(){
        int n=read();
        vector<int>a(n+1),vis(n+1);
        rep(i,1,n+1)a[i]=read();
        int c=0;
        rep(i,1,n+1){
            if(vis[i])continue;
            c++;
            int x=i;
            while(!vis[x]){
                vis[x]=1;
                x=a[x];
            }
        }
        if((n-c+n/2)&1)cout<<"Alice"<<'\n';
        else cout<<"Bob"<<'\n';
    }
    int main(){
        int T=read();
        while(T--){
            solve();
        }
        return 0;
    }
    
    • 1

    Information

    ID
    230
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    7
    Tags
    # Submissions
    36
    Accepted
    10
    Uploaded By