AtCoder - abc152(D,E)

D - Handstand 2

思路:
s(x) 表示 x 的首数字,e(x) 表示 x 的尾数字,v[a][b] 表示以 a开头b结尾的数组的个数。
r e s = ∑ 1 n v [ e ( i ) ] [ s ( i ) ] res = \sum_{1}^{n}v[e(i)][s(i)] res=1nv[e(i)][s(i)]

#include
using namespace std;

int v[10][10];

int s(int x){
	while(x > 9) x /= 10;
	return x;
}

int e(int x){
	return x % 10;
}

int main(){
	
	int n;
	cin >> n;
	for(int i = 1; i <= n; i++) v[s(i)][e(i)]++;
	
	long long res = 0;
	for(int i = 1; i <= n; i++){
		res += v[e(i)][s(i)];
	}
	cout << res << endl;
	
	return 0;
}

E - Flatten

由题意得: r e s = ∑ 1 n l c m ( a 1 , . . . , a n ) a i res = \sum_{1}^{n}\frac{lcm(a_1, ..., a_n)}{a_i} res=1nailcm(a1,...,an)
l c m ( a 1 , . . . , a n ) lcm(a_1, ..., a_n) lcm(a1,...,an) 的求法:定义 c n t i , j cnt_{i,j} cnti,j表示 a i a_i ai 中第 j j j 个质因数的个数, l c m = ∏ i = 1 t o t p o w ( p r i [ i ] , m a x ( c n t 1 , i , . . . c n t n , j ) ) lcm = \prod_{i=1}^{tot}{pow(pri[i], max(cnt_{1,i}, ... cnt_{n,j}))} lcm=i=1totpow(pri[i],max(cnt1,i,...cntn,j))
( t o t tot tot表示欧拉筛之后得到的质数的个数,第 j j j 个质数指欧拉筛的 p r i m e [ j ] prime[j] prime[j])

#include
#define ll long long
using namespace std;

const ll mod = 1e9 + 7;
const int N = 1e6 + 5;

ll vis[N], pri[N], cnt = 0;
ll a[N], v[N];

ll Qpow(ll a, ll b){
	ll res = 1;
	while(b){
		if(b&1) res *= a;
		res %= mod;
		a *= a;
		a %= mod;
		b >>= 1;
	}
	return res;
}

int main(){
	
	for(int i = 2; i < N; i++){
		if(vis[i] == 0) pri[++cnt] = i;
		for(int j = 1; j <= cnt && i * pri[j] < N; j++){
			vis[i * pri[j]] = 1;
			if(i % pri[j] == 0) break;
		} 
	}
	
	int n;
	cin >> n;
	for(int i = 1; i <= n; i++) cin >> a[i];
	
	for(int i = 1; i <= n; i++){
		ll x = a[i];
		for(int j = 1; pri[j] * pri[j] <= x; j++){
			ll num = 0;
			while(x % pri[j] == 0) num++, x /= pri[j];
			v[pri[j]] = max(num, v[pri[j]]);
		}
		if(x != 0) v[x] = max(v[x], 1ll);
	}

	ll lcm = 1, res = 0;
	for(int i = 1; i <= cnt; i++) lcm = lcm * Qpow(pri[i], v[pri[i]]) % mod;
	for(int i = 1; i <= n; i++) res = (res + lcm * Qpow(a[i], mod-2) % mod) % mod;
	
	cout << res << endl;
		
	return 0;
}

你可能感兴趣的:(题解,c++,算法,哈希算法)