经典 DP,费用提前计算的思想。
对于序列类型的 DP 题,我们可以想到用分段型 DP,每次将当前的数插入进去,求解方案数。但是这道题的并费用不好直接计算。
先将 $a$ 排序,并从小到大插入。对于 $i<j$ ,有 $|a_i-a_j|=\sum_{k=i}^{j-1}(a_{k+1}-a_k)$。根据这个我们可以尝试进行费用提前计算。对于之后每个插在当前的 $k$ 个端点上的数,会一共产生 $(a_{i+1}-a_{i})\times k$ 的费用。
状态转移比较套路。注意边界上是没有花费的,所以还需要将边界上填了多少个记录进状态。
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
   | #include<iostream> #include<cstdio> #include<algorithm> #define ll long long using namespace std; const int N=1e2+10,M=1e3+10,mod=1e9+7; template<class T> inline void read(T &x) {     x=0;bool f=0;     char ch=getchar();     while(ch<'0'||ch>'9'){if(ch=='-')f=1;ch=getchar();}     while(ch>='0'&&ch<='9')x=(x<<1)+(x<<3)+(ch^48),ch=getchar();     if(f)x=-x; } template<class T,class ...T1> inline void read(T &x,T1 &...x1) {     read(x),read(x1...); } int n,m; int a[N]; ll f[N][N][M][3]; int main() {     read(n,m);     if(n==1)     {         puts("1");         return 0;     }     for(int i=1;i<=n;i++)         read(a[i]);     sort(a+1,a+1+n);     f[0][0][0][0]=1;     for(int i=0;i<n;i++)         for(int j=0;j<=i;j++)         {             for(int k=0;k<=m;k++)             {                 for(int d=0;d<=2;d++)                 {                     int t=k+(a[i+1]-a[i])*(2*j-d);                     if(t>m||!f[i][j][k][d])continue;                     f[i+1][j+1][t][d]=(f[i+1][j+1][t][d]+f[i][j][k][d]*(j+1-d))%mod;                     if(j)f[i+1][j-1][t][d]=(f[i+1][j-1][t][d]+f[i][j][k][d]*(j-1))%mod;                     if(j)f[i+1][j][t][d]=(f[i+1][j][t][d]+f[i][j][k][d]*(2*j-d))%mod;                     if(d<2)f[i+1][j+1][t][d+1]=(f[i+1][j+1][t][d+1]+f[i][j][k][d]*(2-d))%mod;                     if(j&&d<2)f[i+1][j][t][d+1]=(f[i+1][j][t][d+1]+f[i][j][k][d]*(2-d))%mod;                 }             }         }     ll ans=0;     for(int i=1;i<=m;i++)         ans=(ans+f[n][1][i][2])%mod;     printf("%lld\n",ans);     return 0; }
   |