【BZOJ 3990】 [SDOI2015]排序

.....
看hzwer的题解吧

重要是题目中有一句话 “每种操作最多可以执行一次“ 这很重要!!

#include <cstdio>
#include <iostream>
#define LL long long
using namespace std;
int a[5000],n;
LL ans=0,jc[5000];
inline void Swap(int x,int y,int L)
{
	for(int i=0;i<L;i++) swap(a[x+i],a[y+i]);
}
void Dfs(int L,int cnt)
{
	if(L==n) {ans+=jc[cnt];return;}

	int w1=0,w2=0;
	for(int i=1;i+2*L-1<=n;i+=2*L)
		if(a[i+L-1]+1!=a[i+L])
		{
			if(w1==0) w1=i;
			else if(w2==0) w2=i;
			else  return ;
 		}
 	if(w1==0&&w2==0) Dfs(L*2,cnt);
 	else if(w1!=0&&w2==0)
 	{
 		Swap(w1,w1+L,L);
 		if(a[w1+L-1]+1==a[w1+L]) Dfs(L*2,cnt+1);
 		Swap(w1,w1+L,L);
 	}
 	else
 	{
 		Swap(w1,w2,L);
 		if(a[w1+L-1]+1==a[w1+L]&&a[w2+L-1]+1==a[w2+L]) Dfs(L*2,cnt+1);
 		Swap(w1,w2,L);

 		Swap(w1,w2+L,L);
 		if(a[w1+L-1]+1==a[w1+L]&&a[w2+L-1]+1==a[w2+L]) Dfs(L*2,cnt+1);
 		Swap(w1,w2+L,L);

 		Swap(w1+L,w2,L);
 		if(a[w1+L-1]+1==a[w1+L]&&a[w2+L-1]+1==a[w2+L]) Dfs(L*2,cnt+1);
 		Swap(w1+L,w2,L);

 		Swap(w1+L,w2+L,L);
 		if(a[w1+L-1]+1==a[w1+L]&&a[w2+L-1]+1==a[w2+L]) Dfs(L*2,cnt+1);
 		Swap(w1+L,w2+L,L);
 	}
}
int main()
{
	scanf("%d",&n);
	jc[1]=1;
	for(int i=2;i<=n;i++) jc[i]=jc[i-1]*i;
	n=1<<n;
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
	Dfs(1,0);
	printf("%lld\n",ans);
	return 0;
}
原文地址:https://www.cnblogs.com/ofsxb/p/5113321.html