AcWing 2068. 整数拼接
原题链接
中等
作者:
Value
,
2020-10-12 13:29:32
,
所有人可见
,
阅读 762
暴力O(n * n)
#include <iostream>
#include <cmath>
using namespace std;
const int N = 1E5 + 10;
typedef long long ll;
int arr[N];
int main(){
int n, k; cin >> n >> k;
for(int i = 0; i < n; i ++ ) cin >> arr[i];
ll cnt = 0;
for(int i = 0; i < n - 1; i ++ ){
for(int j = i + 1; j < n; j ++ ){
if(arr[i] % k == 0 && arr[j] % k == 0){
cnt += 2;
continue;
}
ll f = log10(arr[i]), s = log10(arr[j]);
ll num1 = arr[i] * ll(pow(10, s + 1)) + arr[j];
ll num2 = arr[j] * ll(pow(10, f + 1)) + arr[i];
if(num1 % k == 0) cnt ++ ;
if(num2 % k == 0) cnt ++ ;
}
}
cout << cnt << endl;
return 0;
}
优化
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
typedef long long ll;
ll arr[N];
ll cnt[11][N];
ll res = 0;
int n, k;
void work(){
for(int i = 0; i < n; i ++ ){
int cnt_a = log10(arr[i]) + 1; // a的位数
res += cnt[cnt_a][(k - (arr[i] % k)) % k]; // 寻找余数为 k - (arr[i] % k) 的数的个数
for(ll j = 1, power = 10; j <= 10; j ++ ){
ll num = (arr[i] % k) * power % k;
cnt[j][num] ++ ;
power = power * 10;
}
}
}
int main(){
cin >> n >> k;
for(int i = 0; i < n; i ++ ) cin >> arr[i];
work();
reverse(arr, arr + n);
memset(cnt, 0, sizeof cnt);
work();
cout << res << endl;
return 0;
}