NC52894. Circular Coloring
描述
输入描述
The input consists of several test cases and is terminated by end-of-file.
Each test case contains two integers n and m.
输出描述
For each test case, print an integer which denotes the result.
示例1
输入:
1 2 2 3 5000 5000
输出:
6 40 975597525
说明:
For the second sample, there are 10 possible colorings (listed below).C++11(clang++ 3.9) 解法, 执行用时: 866ms, 内存消耗: 67448K, 提交时间: 2019-10-02 21:51:46
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int inf=0x3f3f3f3f; const int mod=1e9+7; const int N=5e3+7; int f[N][N]; int inv[N]; int main() { inv[1]=1; for(int i=2;i<=5000;i++) inv[i]=1LL*(mod-mod/i)*inv[mod%i]%mod; f[0][0]=1; for(int i=1;i<=5000;i++) { int s1=f[i-1][i-1]; int s2=1LL*f[i-1][i-1]*(i-1)%mod; for(int j=i;j<=5000;j++) { f[i][j]=(1LL*s1*j%mod-s2+mod)%mod; s1+=f[i-1][j],s1%=mod; s2+=(1LL*j*f[i-1][j])%mod,s2%=mod; } } int n,m; while(scanf("%d%d",&n,&m)!=EOF) { int lim=min(n,m); int ans=0; for(int i=1;i<=lim;i++) { ans+=1LL*f[i][n]*f[i][m]%mod*inv[i]%mod; ans%=mod; } printf("%d\n",1LL*ans*(n+m)%mod); } return 0; }
C++14(g++5.4) 解法, 执行用时: 689ms, 内存消耗: 98400K, 提交时间: 2020-05-07 09:14:01
#include<bits/stdc++.h> using namespace std; const int N=5005,mod=1e9+7; typedef long long ll; int dp[N][N],inv[N]; int main() { dp[0][0]=inv[1]=1; for(int i=2;i<N;i++) inv[i]=(ll)(mod-mod/i)*inv[mod%i]%mod; for(int i=1;i<=5000;i++) for(int j=1;j<=5000;j++) dp[i][j]=((ll)dp[i-1][j-1]+dp[i][j-1]+dp[i][j-1]-(j-2>=0?dp[i][j-2]:0)+mod)%mod; int n,m; while(scanf("%d%d",&n,&m)!=EOF) { if(n>m) swap(n,m); register ll ans=0; for(int i=1;i<=n;i++) ans=(ans+(ll)dp[i][n]*dp[i][m]%mod*inv[i]%mod); ans%=mod; printf("%lld\n",ans*(n+m)%mod); } }