跳到正文

题解

题解:CF1973E Cat, Fox and Swaps

g1ove约 2 分钟
原文
文章信息与版本

文章信息

发布
2024年5月22日
收录
2026年9月2日
更新
2026年11月14日
篇幅
约 2 分钟
获赞
4
题目
CF1973E

版本

  1. v1当前

先放结论:

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

f(l,r){l=rOthers.l≤n,r≤n[1,r−1]l≤n,r>n[1,n]l>n,r>n[l−n,n]f(l,r) \begin{cases} 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,CA,B,C,如果 A,BA,B 可以互相交换,B,CB,C 可以互相交换,那么 A,CA,C 可以交换。

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

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

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

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

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

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

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

C++
#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;
}
原文
存档评论2 条抓取于