HDU-4689 Derangement DP

时间:2021-10-10 09:54:51

  题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4689

  题意:初始序列1,2...n,求所有满足与初始序列规定大小的错排数目。。

  这道题目感觉很不错~

  题目数据很容易想到用压缩DP,但这题测试数据很多,状压基本都会TLE。。

  f[i][j]表示前 i 个数还有 j 个+号没有放数字,-号全部放满。

  当 i 为+号时:1、当前这个数不放,即放在后面的位置中,f[i][j]+=f[i-1][j-1]。2、当前这个数放在前面的位置中,f[i][j]+=f[i-1][j]*j。所以f[i][j]=f[i-1][j-1]+f[i-1][j]*j。

  当 i 为-号时:1、当前这个数放在后面的位置中,由前面+号未填的数来填-号,f[i][j]+=f[i-1][j]*j。2、当前这个数放在前面的位置中,前面 j 个数放在当前的-号位,当前这个数放在前面未放的+号位,f[i][j]+=f[i-1][j+1]*j*j。

 //STATUS:C++_AC_15MS_232KB
#include <functional>
#include <algorithm>
#include <iostream>
//#include <ext/rope>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <numeric>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <list>
#include <set>
//#include <map>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,102400000")
//using namespace __gnu_cxx;
//define
#define pii pair<int,int>
#define mem(a,b) memset(a,b,sizeof(a))
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define PI acos(-1.0)
//typedef
typedef __int64 LL;
typedef unsigned __int64 ULL;
//const
const int N=;
const int INF=0x3f3f3f3f;
const int MOD=,STA=;
const LL LNF=1LL<<;
const double EPS=1e-;
const double OO=1e15;
const int dx[]={-,,,};
const int dy[]={,,,-};
const int day[]={,,,,,,,,,,,,};
//Daily Use ...
inline int sign(double x){return (x>EPS)-(x<-EPS);}
template<class T> T gcd(T a,T b){return b?gcd(b,a%b):a;}
template<class T> T lcm(T a,T b){return a/gcd(a,b)*b;}
template<class T> inline T lcm(T a,T b,T d){return a/d*b;}
template<class T> inline T Min(T a,T b){return a<b?a:b;}
template<class T> inline T Max(T a,T b){return a>b?a:b;}
template<class T> inline T Min(T a,T b,T c){return min(min(a, b),c);}
template<class T> inline T Max(T a,T b,T c){return max(max(a, b),c);}
template<class T> inline T Min(T a,T b,T c,T d){return min(min(a, b),min(c,d));}
template<class T> inline T Max(T a,T b,T c,T d){return max(max(a, b),max(c,d));}
//End LL f[N][N];
char s[N]; int main(){
// freopen("in.txt","r",stdin);
int i,j,len;
while(~scanf("%s",s))
{
mem(f,);
f[][]=;
len=strlen(s);
for(i=;i<=len;i++){
if(s[i-]=='+'){
for(j=;j<=len;j++)
f[i][j]=f[i-][j-]+f[i-][j]*j;
}
else {
for(j=;j<=len;j++){
f[i][j-]+=f[i-][j]*j*j;
f[i][j]+=f[i-][j]*j;
}
}
} printf("%I64d\n",f[len][]);
}
return ;
}