UVa 11076 (有重元素的排列) Add Again

n个可重复的元素的排列一共有 = All种,其中

假设这些数依次为ai,每种数字有mi个。

从右往左考虑第d位数(d≥0),第i个数字出现的次数为,那么这个数字对所求答案的贡献为

其实可以先一次求出个位上每种数字对答案的贡献,然后乘上

 1 #include <cstdio>
 2 #include <algorithm>
 3 using namespace std;
 4 typedef long long LL;
 5 
 6 const int maxn = 12;
 7 LL fac[maxn + 2], pow10[maxn + 2];
 8 int a[maxn + 2], b[maxn + 2], num[maxn + 2];
 9 
10 int main()
11 {
12     //freopen("in.txt", "r", stdin);
13 
14     fac[0] = pow10[0] = 1;
15     for(int i = 1; i <= maxn; i++) { fac[i] = fac[i-1] * i; pow10[i] = pow10[i-1] * 10; }
16     for(int i = 1; i <= maxn; i++) pow10[i] += pow10[i - 1];
17 
18     int n;
19     while(scanf("%d", &n) == 1 && n)
20     {
21         for(int i = 0; i < n; i++) scanf("%d", &a[i]);
22         sort(a, a + n);
23         int cnt = 0;
24         for(int i = 0; i < n;)
25         {
26             int j = i;
27             while(j < n && a[j] == a[i]) j++;
28             b[cnt] = a[i]; num[cnt++] = j - i;
29             i = j;
30         }
31         LL all = fac[n];
32         for(int i = 0; i < cnt; i++) all /= fac[num[i]];
33         LL sum = 0;
34         for(int i = 0; i < cnt; i++) sum += b[i] * num[i] * all / n;
35         printf("%lld\n", sum * pow10[n-1]);
36     }
37 
38     return 0;
39 }
代码君

 

posted @ 2015-03-22 16:48  AOQNRMGYXLMV  阅读(227)  评论(0编辑  收藏  举报