您的位置:首页 > 运维架构 > Shell

Codeforces 757B Bash's Big Day 【数论】

2017-01-14 16:26 357 查看
本题链接:http://codeforces.com/contest/757/problem/B

题目大意:有 n 个数,问有不为1的公因数的数最多是几个。

思路:

将这 n 个数所有的因数(如果是质数,就是它本身。如果不是质数,就是除1以外的所有因数)都统计在一个数组 times[] 中, times[i] == y 表示这个数(i)是n个数中 y个数的因数,最后统计哪个因数出现的次数多就可以了。

剪枝是:用一个预处理将10^5以内的质数都计算出来,在进行计算会方便的多。

还有,小心被 hack QAQ

#include <cstdio>
#include <iostream>
#include <algorithm>

using namespace std;

const int size = 1e5+5;
int n;
int a[size];

// notpm[i] == 0 表示 i 为素数, notpm[i] == 1 表示 i 不为素数
// pm[i] 表示从 2 开始的第 i 个素数
int notpm[size], pm[size];
int curs = 0;

// Test: #71,
// 10
// 1 1 1 1 1 1 1 1 1 1

void init() { // 利用筛法筛出10^5以内的素数
notpm[1] = 1; // 注意这句话,必须加上!否则会 Wrong answer on test 71
for ( int i = 2; i <= 1e5; i ++ ) {
if(!notpm[i]) {
pm[++ curs] = i;
} else {
for ( int j = i*2; j <= 1e5; j += i ) {
notpm[j] = 1;
}
}
}
}

int times[size];

int mx(int a, int b) { return a>b?a:b; }

int main() {
scanf("%d", &n);
for ( int i = 0; i < n; i++ ) scanf("%d", &a[i]);
init();
for ( int i = 0; i < n; i++ ) {
int temp = a[i];
for ( int j = 1; pm[j]*pm[j] <= temp; j ++ ) {
if(temp%pm[j] == 0) { // 寻找 temp 最小的质因子为最终
times[pm[j]] ++;
while( temp%pm[j] == 0 ) temp /= pm[j];
}
}
if(!notpm[temp]) times[temp] ++; //
4000
对于素数来说,最大的质因子是他自己
}
int ans = 1;

for ( int i = 0; i < size; i++ ) {
ans = mx(ans, times[i]);
}
printf("%d\n", ans);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: