【LG3322】[SDOI2015]排序

题面

洛谷

题解

交换顺序显然不影响答案,所以每种本质不同的方案就给答案贡献次数的阶乘。

从小往大的交换每次至多\(4\)中决策,复杂度\(O(4^n)\)。

代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int MAX_N = 1 << 13;
int N, a[MAX_N];
long long fac[13], ans;
bool check(int x) {
for (int i = 1; i <= 1 << (N - x); i++)
if (a[(i - 1) * (1 << x) + 1] + (1 << (x - 1)) !=
a[(i - 1) * (1 << x) + 1 + (1 << (x - 1))]) return 0;
return 1;
}
void Swap(int p1, int p2, int k) {
for (int i = 0; i < k; i++)
swap(a[p1 + i], a[p2 + i]);
}
void dfs(int x, int p) {
if (x && !check(x)) return ;
if (x == N) return (void)(ans += fac[p]);
dfs(x + 1, p);
int tmp[5], tot = 0;
for (int i = 1; i <= 1 << (N - x); i += 2)
if (a[(i - 1) * (1 << x) + 1] + (1 << x) !=
a[i * (1 << x) + 1]) {
if (tot == 4) return ;
tmp[++tot] = i, tmp[++tot] = i + 1;
}
if (!tot) return ;
for (int i = 1; i <= tot; i++)
for (int j = i + 1; j <= tot; j++) {
Swap((1 << x) * (tmp[i] - 1) + 1, (1 << x) * (tmp[j] - 1) + 1, 1 << x);
dfs(x + 1, p + 1);
Swap((1 << x) * (tmp[i] - 1) + 1, (1 << x) * (tmp[j] - 1) + 1, 1 << x);
}
}
int main () {
#ifndef ONLINE_JUDGE
freopen("cpp.in", "r", stdin);
#endif
fac[0] = 1;
for (int i = 1; i < 13; i++) fac[i] = fac[i - 1] * i;
scanf("%d", &N);
for (int i = 1; i <= 1 << N; i++) scanf("%d", a + i);
dfs(0, 0);
printf("%lld\n", ans);
return 0;
}

最新文章

  1. 10. 星际争霸之php设计模式--原型模式
  2. mysql insert一条记录后怎样返回创建记录的主键id,last_insert_id(),selectkey
  3. Command
  4. HTML5每日一练之details展开收缩标签的应用
  5. [o] SQLite数据库报错: Invalid column C
  6. LeetCode——Valid Palindrome
  7. lseek() 定位一个已经打开的文件
  8. Projecet客户端登陆无法通过验证
  9. LaTeX新人30分钟从完全陌生到基本入门
  10. javase
  11. url重写步骤
  12. NopCommerce用core重写ef
  13. php 解密$OOO0O0O00=__FILE__
  14. js计算器---转
  15. javascript从作用域到闭包-笔记
  16. 详解webpack中的hash、chunkhash、contenthash区别
  17. win7颜色反转
  18. Django实现websocket完成实时通讯、聊天室、在线客服等
  19. 在win10下安装双系统ubuntu16.04.3教程
  20. apache中配置php支持模块模式、cgi模式和fastcgi模式

热门文章

  1. Linux操作USB手柄
  2. 微服务浅谈&amp;服务治理的演变过程
  3. [转帖]k8s 中的服务如何沟通
  4. Sentry异常捕获平台
  5. jdk1.8 Stream 特性总结
  6. Java如何执行操作系统的CMD命令行
  7. Prometheus 监控Docker服务器及Granfanna可视化
  8. spring-session(二)与spring-boot整合实战
  9. 【ELK】elasticsearch中使用脚本报错:scripts of type [inline], operation [update] and lang [groovy] are disabled
  10. 一段简单的顶部JS广告