UVA 11076 Add Again(有重複元素的全排列問題)

UVA 11076 Add Again

題意:

輸入N個數字,求這幾個數字組成的數之和。
如:1,2,3.組成的數有123,132,213,231,312,321,和爲1332.

思路:

有重複元素的全排列類問題:
有k個元素,第 i 個元素 aici 個,設總的全排列個數爲 x。
那麼:設共有 n 個元素(n=ai ),得方程

a1!a2!ak!x=n!

得到全排列個數 x ,進而得到每一個數字在每一位出現的次數爲 x / n。
例如:
1,2,2每一個數字在每一位出現的次數爲 3/3 = 1;
1,2,3每一個數字在每一位出現的次數爲 6/3 = 2。

回到求和問題,
<1,2,3>組成的數字有:
123
132
213
231
312
321
sum = (6 * 2)(6 * 2)(6 * 2)
換成十進制即 sum = 12*10^2 + 12 * 10 + 12 = 1332。
綜上,
答案的每一位 = 所有數字之和乘以出現次數,
sum=x/naici11..11(n1)

代碼:

//#pragma comment(linker, "/STACK:102400000,102400000")
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <functional>
#include <string>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <stack>
#include <bitset>

using namespace std;

#define IOS std::ios::sync_with_stdio(false);std::cin.tie(0)
#define clr( x , y ) memset(x,y,sizeof(x))
#define cls( x ) memset(x,0,sizeof(x))
#define pr( x ) cout << #x << " = " << x << endl
#define pri( x ) cout << #x << " = " << x << " "
#define test( t ) int t ; cin >> t ; int kase = 1 ; while( t-- )
#define out( kase ) printf( "Case %d: " , kase++ )
#define mp make_pair
#define pii pair<int,int>
#define pli pair<long long,int>
#define pll pair<long long,long long>
#define fs first
#define se second
#define pb push_back
typedef long long lint;
typedef long long ll;
typedef long long LL;
typedef unsigned long long ULL;
const double eps = 1e-8 ;
const int inf = 0x3f3f3f3f ;
const long long INF = 0x3f3f3f3f3f3f3f3fLL ;

// const int N = ;
int num[20] , a[20] ;
lint fac[20] ;
lint basic[] = { 1 , 11 , 111 , 1111 , 11111 , 111111 , 1111111 , 11111111 , 111111111 ,1111111111 ,11111111111 , 111111111111 } ;
int n ;
void init()
{
    fac[0] = 1 ;
    for ( int i = 1 ; i < 20 ; i++ )
        fac[i] = fac[i-1] * i ;

}
void work()
{
    lint ans = 0 ;
    cls( num ) ;
    for ( int i = 0 ; i < n ; i++ ) {
        scanf( "%d" , a + i ) ;
        ans += a[i] ;
        num[a[i]] ++ ;
    }
    lint x = fac[n] ;
    for (int i = 0; i < 10 ; i++) {
        x /= fac[num[i]] ;
    }
    ans = ans * x * basic[n-1] / n ;
    cout << ans << endl ;
}
int main()
{
    // freopen("my.in","r",stdin);
    // freopen("my.out","w",stdout);
    init() ;
    while( cin >> n && n ) {
        work() ;
    }
    return 0;
}
發佈了127 篇原創文章 · 獲贊 14 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章