Question:
Summation of sequence of integers is always a common problem in Computer Science. Rather than
computing blindly, some intelligent techniques make the task simpler. Here you have to find the summation
of a sequence of integers. The sequence is an interesting one and it is the all possible permutations
of a given set of digits. For example, if the digits are <1 2 3>, then six possible permutations are
<123>, <132>, <213>, <231>, <312>, <321> and the sum of them is 1332.
Input
Each input set will start with a positive integer N (1 ≤ N ≤ 12). The next line will contain N decimal
digits. Input will be terminated by N = 0. There will be at most 20000 test set.
Output
For each test set, there should be a one line output containing the summation. The value will fit in
64-bit unsigned integer.
Sample Input
3
1 2 3
3
1 1 2
0
Sample Output
1332
444
题意大意:给你n个数字,让你将他们任意排序(但组成的为同一数字算作一个数字),并求出他们的和,例如:1,2,3可组成123,132,213,231,312,321。。。契合为1332。
思路:计算每个数字出现的次数,然后定住任意一个数字,将其拿出来,让其他的数任意排列,总数为这些数字组合加载一起,但注意去重的时候可能失误,要将指定那个数拿出来(即将这个数字的个数减一),否则会去重多去掉。
(http://acm.hust.edu.cn/vjudge/contest/121559#problem/F)
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
typedef long long LL;
LL sum,f[15];
int main()
{
int n,x,a[10];
f[0]=1;
for(int i=1;i<=12;i++)
f[i]=f[i-1]*i;
while (scanf("%d",&n),n)
{
sum=0;
memset(a,0,sizeof(a));
for(int i=0;i<n;i++)
{
scanf("%d",&x);
a[x]++;
}
LL temp=1,t;
for(int i=0;i<n;i++)
{
for(int j=0;j<10;j++)
{
if(!a[j])
continue;
a[j]--; //注意此处将选中的那个数的个数减一,避免多次去重
t=j*f[n-1];
for(int k=0;k<10;k++)
t/=f[a[k]];
t*=temp;
sum+=t;
a[j]++; //但是去重后要将这个数加上,否则会对下次其他数字排序产生影响
}
temp*=10;
}
printf("%lld\n",sum);
}
return 0;
}
体会:本弱就走进了去重的误区,可能是自己数学不好吧,深深体会到数学的重要性。发誓一定要好好学习数学