考虑套路地将1~n依次加入排列。设f[i][j]为已将1~i加入排列,有j对不合法的方案数。加入i+1时可能减少一对不合法的,可能不变,可能增加一对,对于i+1与i的关系再增设0/1/2状态表示i与左边/右边的数是否构成不合法对即可。
#include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; int read() { int x=0,f=1;char c=getchar(); while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();} while (c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar(); return x*f; } #define N 1010 #define P 7777777 int n,f[N][N][3]; void inc(int &x,int y){x+=y;if (x>=P) x-=P;} int main() { #ifndef ONLINE_JUDGE freopen("bzoj4321.in","r",stdin); freopen("bzoj4321.out","w",stdout); const char LL[]="%I64d "; #else const char LL[]="%lld "; #endif n=read(); f[1][0][0]=1; for (int i=2;i<=n;i++) for (int j=0;j<i;j++) { inc(f[i][j][0],(1ll*f[i-1][j][0]*(i-2-j)+1ll*(f[i-1][j][1]+f[i-1][j][2])*(i-1-j))%P); inc(f[i][j][0],(1ll*f[i-1][j+1][0]*(j+1)+1ll*(f[i-1][j+1][1]+f[i-1][j+1][2])*j)%P); if (j) inc(f[i][j][1],(f[i-1][j-1][0]+f[i-1][j-1][1])%P);inc(f[i][j][1],f[i-1][j][2]); if (j) inc(f[i][j][2],(f[i-1][j-1][0]+f[i-1][j-1][2])%P);inc(f[i][j][2],f[i-1][j][1]); } cout<<f[n][0][0]; return 0; }