卡不過去了,求調

无敌の暗黑魔王發表於2024-09-26

TLE95
#include<iostream>
#include<map>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/hash_policy.hpp>
#define ll long long
#pragma GCC optimize(5)
#pragma GCC optimize("Ofast")
const ll N=5e3+10,p=1e9+7;
__gnu_pbds::cc_hash_table<ll,ll>f[N];
ll fact[N],n,m,t,ny[N],nyp[N],k;
inline ll qum(ll a,ll b){
	ll ans=1;
	while(b){
		(b&1)&&(ans=ans*a%p);
		a=a*a%p;
		b>>=1;
	}
	return ans;
}
signed main(){
    // freopen("1.in","r",stdin);
    freopen("capital.in","r",stdin);
    freopen("capital.out","w",stdout);
	scanf("%lld",&t);fact[0]=1;
	for(short i=1;i<=1000;i=-~i)fact[i]=fact[i-1]*i%p;
	ny[1000]=qum(fact[1000],p-2);
	for(short i=999;i;i=~-i)ny[i]=ny[i+1]*(i+1)%p;
    for(short i=1;i<=1000;i=-~i)nyp[i]=fact[i-1]*ny[i]%p;
	while(t--){
		scanf("%lld%lld",&n,&m);
		ll ans=0;
		for(int i=m-n;i<=m;i=-~i)f[0][i]=1;
		for(k=1;k<n;k=-~k){
			f[k][1]=ny[k];
			for(int i=m-n/k;i<=m;i=-~i){
                for(int j=1;j<=k;j=-~j){
                    f[j][i]=nyp[j]*i%p*f[j-1][i]%p;
                }
                for(int j=k+1;j<=n;j++){
                    f[j][i]=nyp[j]*i%p*(f[j-1][i]-ny[k]*f[j-k-1][i-1]%p+p)%p;
                }
            }
            ans+=f[n][m];
		}
        for(int j=1;j<=n;j=-~j){
            f[j][m-1]=nyp[j]*(m-1)%p*f[j-1][m-1]%p,
            f[j][m]=nyp[j]*m%p*f[j-1][m]%p;
        }ans=(n*f[n][m]%p-ans%p+p)%p;
		printf("%lld\n",ans*fact[n]%p);
	}
}
原始程式碼
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/hash_policy.hpp>
const int N=1e3+10,p=1e9+7;
__gnu_pbds::cc_hash_table<int,int>f[N];
int fact[N],n,m,t,ny[N],nyp[N],k;
inline int max(int x,int y){return x>y?x:y;}
inline int qum(int a,int b){
	int ans=1;
	while(b){
		(b&1)&&(ans=1ll*ans*a%p);
		a=1ll*a*a%p;
		b>>=1;
	}
	return ans;
}
signed main(){
    freopen("capital.in","r",stdin);
    freopen("capital.out","w",stdout);
	scanf("%d",&t);fact[0]=1;
	for(int i=1;i<=1000;i=-~i)fact[i]=1ll*fact[i-1]*i%p;
	ny[1000]=qum(fact[1000],p-2);
	for(int i=999;i;i--)ny[i]=1ll*ny[i+1]*(i+1)%p;
    for(int i=1;i<=1000;i=-~i)nyp[i]=1ll*fact[i-1]*ny[i]%p;
	while(t--){
		scanf("%d%d",&n,&m);
		int ans=0;
		for(int i=m-n;i<=m;i=-~i)f[0][i]=1;
		for(k=1;k<=n;k=-~k){
			f[k][1]=ny[k];
			for(int i=max(m-n/k,1);i<=m;i=-~i)
				for(int j=1;j<=n;j=-~j)
					f[j][i]=1ll*nyp[j]*i%p*(f[j-1][i]-((j-k-1>=0)?1ll*ny[k]*f[j-k-1][i-1]:0)%p+p)%p;
            ans=(k^n)?(ans+f[n][m])%p:(1ll*n*f[n][m]%p-ans+p)%p;
		}
		ans=1ll*ans*fact[n]%p;
		printf("%d\n",ans);
	}
}

相關文章