题解:CF1973E Cat, Fox and Swaps

· · 题解

先放结论:

定义 f(l,r) 表示选择 [l,r] 的操作区间。这个区间内的数可以任意交换。

l=r & Others.\\ l\le n,r\le n & [1,r-1] \\ l\le n,r>n & [1,n]\\ l>n,r>n & [l-n,n] \end{cases}

证明:

首先,我们知道,如果对于三个数 A,B,C,如果 A,B 可以互相交换,B,C 可以互相交换,那么 A,C 可以交换。

构造一种方案:(A,B,C)\to (B,A,C)\to (C,A,B)\to (C,B,A)

所以我们可以得到上面的结论。

有了这个,我们画个图,发现除了 l=r 这种特殊情况,其它情况通过画图可以自己手推,只需要一对相邻的数 (x,x+1) 就可以把所有数连起来。

注意边界。讨论完可以得到上面的结论。

最后是 l=r 的情况,这个把所有要操作交换的和记下来,如果只有一种和,那就是合法的。

上面的都懂了,统计答案就不难了,记两个极值,使用等差数列公式求和即可。因为最小值以上的和最大值以下的都需要交换。

时间复杂度是 O(n) 的。

#include<bits/stdc++.h>
#define ll long long
#define N 100005
using namespace std;
int g;
int n,a[N];
ll res;
int pos;
int maxx,minn;
int main()
{
    scanf("%d",&g);
    while(g--)
    {
        res=0;
        scanf("%d",&n);
        pos=-1;
        maxx=0;minn=1e9;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            if(i==a[i]) continue;
            if(pos==-1) pos=a[i]+i;
            else if(pos^(a[i]+i)) pos=-2;
            maxx=max(maxx,a[i]);
            minn=min(minn,a[i]);
        }
        if(minn==1e9)
        {
            printf("%lld\n",1ll*n*(n*2+1));
            continue;
        }
        if(pos>0) res=1;
        // Case 1:
        res+=1ll*(maxx+n-1)*(n-maxx)/2;
        // Case 2:
        res+=1ll*n*n;
        // Case 3:
        res+=1ll*n*minn-1ll*(minn+1)*(minn)/2;
        printf("%lld\n",res);
    }
    return 0;
}