Advertisement
Guest User

zx

a guest
Mar 7th, 2016
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class Permutant {
  4.   public int mod = 1000000007;
  5.   public int counthis(int[] a) {
  6.     int n = a.length;
  7.     int m = 0;
  8.     for (int x : a) m += x;
  9.     long[][] comb = new long[m+1][m+1];
  10.     comb[0][0] = 1;
  11.     for (int i = 1; i <= m; i++) {
  12.       comb[i][0] = 1;
  13.       for (int j = 1; j <= i; j++) {
  14.         comb[i][j] = (comb[i-1][j] + comb[i-1][j-1]) % mod;
  15.       }
  16.     }
  17.     long[] fact = new long[m+1];
  18.     fact[0] = 1;
  19.     for (int i = 1; i <= m; i++) {
  20.       fact[i] = fact[i-1] * i % mod;
  21.     }
  22.    
  23.     long ret = 0;
  24.     for (int last = 0; last < n; last++) {
  25.       // dp[i] = number of ways given there are i balls to the right of the first occurrence of a ball of the last color.
  26.       long[] dp = new long[m+1];
  27.       // can freely arrange all the balls of the last color
  28.       dp[a[last] - 1] = fact[a[last]];
  29.       int cursum = a[last]-1;
  30.       for (int i = 0; i < n; i++) {
  31.         if (last == i) continue;
  32.         long[] next = new long[m+1];
  33.         // need to put at least one ball to the left
  34.         for (int left = 1; left <= a[i]; left++) {
  35.           int right = a[i] - left;
  36.           for (int curright = 0; curright <= cursum && curright+right <= m; curright++) {
  37.             int curleft = cursum - curright;
  38.             // since the first occurrence of each color needs to be label 1, this is fact[a[i]-1] instead of fact[a[i]].
  39.             long y = fact[a[i]-1] * comb[curleft+left][left] % mod * comb[curright+right][right] % mod;
  40.             next[curright+right] = (next[curright+right] + dp[curright] * y) % mod;
  41.           }
  42.         }
  43.         dp = next;
  44.         cursum += a[i];
  45.       }
  46.       for (int i = 0; i <= m; i++)
  47.         ret = (ret + dp[i]) % mod;
  48.     }
  49.     return (int)ret;
  50.   }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement