Circular Coloring
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 132768/132768 K (Java/Others)Total Submission(s): 28 Accepted Submission(s): 10
Problem Description
Bobo considers
(n+m) balls arranged in a circle.
The balls are numbered with 0,1,…,(n+m−1) where the ball i and the ball (i+1)mod(n+m) are adjacent.
Bobo would like to color n of his balls black and m of his balls white.
Bobo groups adjacent balls with same colors, and he determines the weight of the coloring as the product of the lengths of groups.
He would like to know the sum of the weight of the possible colorings, modulo (109+7).
The balls are numbered with 0,1,…,(n+m−1) where the ball i and the ball (i+1)mod(n+m) are adjacent.
Bobo would like to color n of his balls black and m of his balls white.
Bobo groups adjacent balls with same colors, and he determines the weight of the coloring as the product of the lengths of groups.
He would like to know the sum of the weight of the possible colorings, modulo (109+7).
Input
The input consists of several test cases and is terminated by end-of-file.
Each test case contains two integers n and m.
Each test case contains two integers n and m.
Output
For each test case, print an integer which denotes the result.
## Constraint
* 1≤n,m≤5000
* The number of test cases does not exceed 5000.
## Constraint
* 1≤n,m≤5000
* The number of test cases does not exceed 5000.
Sample Input
1 22 35000 5000
Sample Output
640975597525
Hint
For the second sample, there are $10$ possible colorings (listed below).The number followed is the corresponding weight.* `BBWWW` ($6$)* `BWBWW` ($2$)* `BWWBW` ($2$)* `BWWWB` ($6$)* `WBBWW` ($6$)* `WBWBW` ($2$)* `WBWWB` ($2$)* `WWBBW` ($6$)* `WWBWB` ($2$)* `WWWBB` ($6$)
Source
Recommend
解法:dp,注意将(头部和尾部)从整体中分开来讨论,则剩下部分为一条链,用两次前缀和优化即可。
以第一维为起始颜色,now[0]相当于以第一维的颜色结束,now[1]相当于以第二维的颜色结束。
#include"bits/stdc++.h"
using namespace std;
const int mod = 1e9+7;
const int MX = 5002;
typedef long long LL;
int dp[MX][MX],now[2],si1[MX],si2[MX],sj1[MX],sj2[MX];
void init()
{
int n = 5000, m = 5000;
for(int i = 0; i <= n; i++)
dp[i][0] = dp[0][i]= sj1[i] = sj2[i] = i;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
now[0] = si2[j]%mod;
now[1] = sj2[i]%mod;
dp[i][j] = now[0];
(si1[j] += now[1]) %= mod;
(sj1[i] += now[0]) %= mod;
(si2[j] += si1[j]) %= mod;
(sj2[i] += sj1[i]) %= mod;
}
}
}
LL work(int n, int m){
LL ans = 0;
for(int i = 1; i <= n; i++)
(ans += (LL) i*i*dp[m][n-i]) %= mod;
for(int j = 1; j <= m; j++)
(ans += (LL) j*j*dp[n][m-j]) %= mod;
cout<<ans<<endl;
}
int main()
{
init();
int n,m;
while(~scanf("%d%d",&n,&m)){
work(n,m);
}
}