1. 程式人生 > >Codeforces Round #428 (Div. 2) D. Winter is here[數論II][容斥原理]

Codeforces Round #428 (Div. 2) D. Winter is here[數論II][容斥原理]

note efi force its eps page http ref esp

傳送門:http://codeforces.com/contest/839/problem/D

技術分享

Examples input
3
3 3 1
output
12
input
4
2 3 4 6
output
39
Note

In the first sample the clans are {1},?{2},?{1,?2} so the answer will be 1·3?+?1·3?+?2·3?=?12

題解:當有n個數為x的倍數時 gcd為x對答案的貢獻為$1*C_n^1+2*C_n^2+...+n*C_n^n$

避免重復,從後向前計算,用f[x]表示gcd為x時存在的貢獻組數,例如計算x,則在x的情況基礎上減去f[2x]、f[3x]....

二項式定理:$(x+y)^n=C_n^0x^ny^0+C_n^1*x^{n-1}*y^1......$令x=y=1得$0*C_n^0+1*C_n^1+2*C_n^2+...+n*C_n^n=n*2^{n-1}$

 1 #define _CRT_SECURE_NO_DEPRECATE
 2 #pragma comment(linker, "/STACK:102400000,102400000")
 3 #include<iostream>  
 4 #include<cstdio>  
 5 #include<fstream>  
 6 #include<iomanip>
 7
#include<algorithm> 8 #include<cmath> 9 #include<deque> 10 #include<vector> 11 #include<bitset> 12 #include<queue> 13 #include<string> 14 #include<cstring> 15 #include<map> 16 #include<stack> 17 #include<set> 18 #include<functional> 19
#define pii pair<int, int> 20 #define mod 1000000007 21 #define mp make_pair 22 #define pi acos(-1) 23 #define eps 0.00000001 24 #define mst(a,i) memset(a,i,sizeof(a)) 25 #define all(n) n.begin(),n.end() 26 #define lson(x) ((x<<1)) 27 #define rson(x) ((x<<1)|1) 28 #define inf 0x3f3f3f3f 29 typedef long long ll; 30 typedef unsigned long long ull; 31 using namespace std; 32 const int maxn = 1e6 + 5; 33 ll savepow[maxn]; 34 int cnt[maxn]; 35 ll f[maxn]; 36 int main() 37 { 38 ios::sync_with_stdio(false); 39 cin.tie(0); cout.tie(0); 40 int i, j, k, m, n; 41 cin >> n; 42 for (int i = 1; i <= n; ++i) 43 { 44 cin >> k; 45 cnt[k]++; 46 } 47 savepow[0] = 1; 48 for (int i = 1; i <= 1000000; ++i)savepow[i] = (savepow[i - 1] << 1) % mod; 49 ll ans = 0; 50 for (ll i = 1000000; i > 1; --i) 51 { 52 int sum = 0; 53 for (int j = i; j <= maxn; j += i) 54 sum += cnt[j]; 55 if (sum) 56 { 57 ll tempans = 0; 58 tempans = 1LL * sum*savepow[sum - 1] % mod; 59 for (int j = i + i; j <= maxn; j += i) 60 tempans = (tempans - f[j] + mod) % mod; 61 f[i] = tempans; 62 ans = (ans + i*f[i]) % mod; 63 } 64 } 65 cout << ans << endl; 66 return 0; 67 }

Codeforces Round #428 (Div. 2) D. Winter is here[數論II][容斥原理]