PROBLEM:
Given n digits number-N. (n<=12, so that ans always fit in 64-bit int) .
We have to calculate the sum of all of its permutation numbers.
for example:
N= 123. Then, n is 3 (digits.)
123
132
213
231
312
321
------
1332
Here, if we fixed '1' in first postion,then we can arrange remaining digits in (n-1)! ways.
so, 1 can be in pos-0 in (n-1)! times. so, add- (1* fac[n-1]*dig[pos] )=1*2*1
1 can be in pos-1 in (n-1)! times. so,add = 1*2*10=20;
1 can be in pos-2 in (n-1)! times. so,add = 1*2*100=200;
Overall for 1=220.
similarly, for 2=444
for 3=666
--------------
so, ans= 1322.
NOW, consider if digits are not unique then ??
----->> Nothing to be amazed, Just multiply -- (n-1)! by occurace of remaining digits except fixed one.
Suppose for 3 digit number - 1 1 2
Here, if we fix 1 then, for every digit position multiply ans & add- 1*2!*dig[pos...]. = 220
finally, if we fix 2 then, for every digit pos multiply ans & add- 2* 2!/2!(repetation of 1) *dig[pos.] =220
So, the answer is 444.
Suppose for 10 digits number as below:
1 4 4 1 2 2 6 6 6 1
after fixing -'1' ==> 9!/2!(remaining two 1s)*2!(for 4)*2!(for 2)*3!(for 6) .
similarly, fix -2,4,6 and do above procedure, then we will get the desired answer=92399999990760.
My solution:
#include<bits/stdc++.h>
#define PI acos(-1.0)
#define M 346350
#define S(a) scanf("%lld",&a)
#define clr(a) memset(a,0,sizeof(a))
#define pb(x) push_back(x)
#define all(v) v.begin(),v.end()
#define fr(i,a,n) for(i=a;i<=n;i++)
using namespace std;
typedef long long ll;
int main()
{
ll n,m,t,a,b,i,j,k,x,tc,cs=1,fac[14],fr[12],dig[14];
fac[0]=1;
dig[0]=1;
fr(i,1,12)
{
fac[i]=fac[i-1]*i;
dig[i]=dig[i-1]*10;
}
while(S(n) && n)
{
vector<ll>v;
clr(fr);
fr(i,1,n)
{
S(x);
fr[x]++;
if(fr[x]==1)v.pb(x);
}
int sz=v.size();
ll sm=0;
fr(i,0,sz-1)
{
fr[v[i]]--;
ll fc=fac[n-1];
fr(j,0,sz-1)
{
fc/=fac[fr[v[j]]];
}
ll mul=0;
fr(j,0,n-1)
{
mul+=dig[j];
}
fr[v[i]]++;
sm+=(v[i]*fc*mul);
}
printf("%lld\n",sm);
}
return 0;
}
Comments
Post a Comment