3990: [SDOI2015]排序
Time Limit: 20 Sec Memory Limit: 128 MBSubmit: 590 Solved: 303
[ Submit][ Status][ Discuss]
Description
小A有一个1-2^N的排列A[1..2^N],他希望将A数组从小到大排序,小A可以执行的操作有N种,每种操作最多可以执行一次,对于所有的i(1<=i<=N),第i中操作为将序列从左到右划分为2^{N-i+1}段,每段恰好包括2^{i-1}个数,然后整体交换其中两段.小A想知道可以将数组A从小到大排序的不同的操作序列有多少个,小A认为两个操作序列不同,当且仅当操作个数不同,或者至少一个操作不同(种类不同或者操作位置不同).
下面是一个操作事例:
N=3,A[1..8]=[3,6,1,2,7,8,5,4].
第一次操作,执行第3种操作,交换A[1..4]和A[5..8],交换后的A[1..8]为[7,8,5,4,3,6,1,2].
第二次操作,执行第1种操作,交换A[3]和A[5],交换后的A[1..8]为[7,8,3,4,5,6,1,2].
第三次操作,执行第2中操作,交换A[1..2]和A[7..8],交换后的A[1..8]为[1,2,3,4,5,6,7,8].
Input
第一行,一个整数N
第二行,2^N个整数,A[1..2^N]
Output
一个整数表示答案
Sample Input
3
7 8 5 6 1 2 4 3
7 8 5 6 1 2 4 3
Sample Output
6
HINT
100%的数据, 1<=N<=12.
Source
先想些例子
比如有一串数字 1 2 3 4
这是一组4连续有序的东西
如果你考虑把它拆开,,,每种长度的操作只能有一次
所以,,,好像你就搞不回来了??
因此,从小到大处理操作
对于2^i,,首先保证所有2^(i-1)次方的小块都得有序
然后考虑2^i的交换
发现这些2^i的块,要么块内有序,你不能动他
要么块内前后两半不能连续,,记为tot += 2
tot这个东西显然不能超过4,不然就没有办法了
还有,如果对于2^i大小的块,你不能保证所有这样的东西块内有序的话
再搜下去也是无意义的
于是,,两个剪枝,爆搜一下下
#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
#include<bitset>
#include<algorithm>
#include<cstring>
#include<map>
#include<stack>
#include<set>
#include<cmath>
#include<ext/pb_ds/priority_queue.hpp>
using namespace std;
const int maxn = 1<<15;
typedef long long LL;
int n,num[maxn];
LL ans,fac[13];
void Swap(int l,int r,int len) {for (int i = 0; i < len; i++) swap(num[l+i],num[r+i]);}
void Dfs(int len,int tot)
{
if (len > n) {
for (int i = 1; i <= n; i++)
if (num[i] != i) return;
ans += fac[tot]; return;
}
int pos[5],TOT = 0;
for (int i = 1; i <= n; i += len) {
if (num[i + len/2] - num[i] == len/2) continue;
if (TOT == 4) return;
pos[++TOT] = i; pos[++TOT] = i + len/2;
}
if (TOT == 2) {
Swap(pos[1],pos[2],len/2);
if (num[pos[2]] - num[pos[1]] == len/2) Dfs(len*2,tot+1);
Swap(pos[1],pos[2],len/2);
}
else if (TOT == 4) {
for (int i = 1; i < 4; i++)
for (int j = i+1; j <= 4; j++) {
Swap(pos[i],pos[j],len/2);
if (num[pos[2]] - num[pos[1]] == len/2 && num[pos[4]] - num[pos[3]] == len/2)
Dfs(len*2,tot+1);
Swap(pos[i],pos[j],len/2);
}
}
else Dfs(len*2,tot);
}
int main()
{
#ifdef DMC
freopen("DMC.txt","r",stdin);
#endif
cin >> n; fac[0] = 1;
for (LL i = 1; i <= n; i++) fac[i] = i*fac[i-1];
n = 1<<n;
for (int i = 1; i <= n; i++) scanf("%d",&num[i]);
Dfs(2,0);
cout << ans;
return 0;
}