hdu 5225 Tom and permutation(回溯)
2015-07-29 00:17
309 查看
题目链接:hdu 5225 Tom and permutation
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 100;
const int mod = 1e9+7;
int N, ans, V[maxn + 5], A[maxn + 5];
ll S[maxn + 5], L[maxn + 5];
int query(int x) {
int ret = 0;
for (int i = 1; i < x; i++) {
if (V[i] == 0)
ret++;
}
return ret;
}
int dfs(int d, int s) {
if (d > N)
return 0;
if (s == 0) {
ans = (ans + S[N-d+1]) % mod;
return L[N-d+1];
} else {
int ret = 0;
for (int i = 1; i <= A[d]; i++) {
if (V[i]) continue;
V[i] = 1;
int s = query(i);
ll temp = dfs(d + 1, i == A[d] ? 1 : 0);
ans = (ans + temp * s % mod) % mod;
ret = (ret + temp) % mod;
V[i] = 0;
}
return ret;
}
}
int main () {
S[1] = 0;
L[1] = 1;
for (int i = 2; i <= maxn; i++) {
S[i] = S[i-1] * i % mod+ L[i-1] * ((1LL * i * (i-1) / 2) % mod) % mod;
L[i] = L[i-1] * i % mod;
}
while (scanf("%d", &N) == 1) {
ans = 0;
memset(V, 0, sizeof(V));
for (int i = 1; i <= N; i++)
scanf("%d", &A[i]);
dfs(1, 1);
printf("%d\n", ans);
}
return 0;
}
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 100;
const int mod = 1e9+7;
int N, ans, V[maxn + 5], A[maxn + 5];
ll S[maxn + 5], L[maxn + 5];
int query(int x) {
int ret = 0;
for (int i = 1; i < x; i++) {
if (V[i] == 0)
ret++;
}
return ret;
}
int dfs(int d, int s) {
if (d > N)
return 0;
if (s == 0) {
ans = (ans + S[N-d+1]) % mod;
return L[N-d+1];
} else {
int ret = 0;
for (int i = 1; i <= A[d]; i++) {
if (V[i]) continue;
V[i] = 1;
int s = query(i);
ll temp = dfs(d + 1, i == A[d] ? 1 : 0);
ans = (ans + temp * s % mod) % mod;
ret = (ret + temp) % mod;
V[i] = 0;
}
return ret;
}
}
int main () {
S[1] = 0;
L[1] = 1;
for (int i = 2; i <= maxn; i++) {
S[i] = S[i-1] * i % mod+ L[i-1] * ((1LL * i * (i-1) / 2) % mod) % mod;
L[i] = L[i-1] * i % mod;
}
while (scanf("%d", &N) == 1) {
ans = 0;
memset(V, 0, sizeof(V));
for (int i = 1; i <= N; i++)
scanf("%d", &A[i]);
dfs(1, 1);
printf("%d\n", ans);
}
return 0;
}
相关文章推荐
- Java多态学习总结
- 黑马程序员——Java基础---泛型、集合框架工具类:Collections和Arrays、JDK 1.5新特性
- 第2讲 zookeeper 集群环境的搭建与测试
- hdu5317 RGCDQ 统计
- [C++]strcpy和strcpy_s安全性比较
- Swift入门(一)——基本语法
- Android中Handler的使用
- hdu 5125 magic balls(dp)
- HDU1501(dfs)
- 插入排序
- 放下8件事,净化你的心灵
- CodeForces 349B - Color the Fence
- 埃及分数(迭代加深搜)
- iis 更改asp.net 版本设置
- hdu 5124 lines(贪心)
- MFC程序打开文件对话框出错的问题解决
- 杭电1896 Stones
- python多线程
- 安装星际译王
- linux查看和关闭后台执行程序