Acwing1291_约数的使用+枚举

题目链接:https://www.acwing.com/problem/content/1293/

题目大意:
给出一些数,然后想要得到对于每个数字而言,有多少个数字可以整除它;

解题过程:
首先想到最暴力的做法,直接对于每个数都去遍历一遍,这样写的时间复杂度是O(n * n)会超时。
然后,这道题目让我们去找这个数有多少个约数,但是其实对于RSA密码学中其实分解因数比求乘积难很多,这个思想同样可以使用道这道题目中;由于暴力的方法是不行的,所以思路就很确定了,应该是存在着一种预处理的方式来进行实现,而且O(n)的时间复杂度基本是不可能的,那么不出意外这道题目应该是需要采用一种方法来达到O(nlogn)的时间复杂度;
最终,有一种方法恰好可以满足;就是我们可以先求每个一数字的倍数,即去先处理一下每一个数字是多少个已存在数字的因子,这样反过来去写,这样的话极限时间复杂度是:n / 1 + n / 2 + n / 3 + … + n/ n = 0(nlogn);
当然,中间也有一些细节需要注意,不用去算已经计算过的数字,要不然可能会超时(我就超时了一次)

代码一份:

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

using namespace std;

const int N = 1e5 + 5, M = 1e6 + 5;
const int inf = 0x3f3f3f3f;

struct Node {
	int x;
	int idx;
}a[N];
int cnt[M];
int f[N];
bool vis[M];
int permt[M];

int main(void) {
//	freopen("in.txt", "r", stdin);
	int n; 
	scanf("%d", &n);
	
	int minn = inf, maxx = 0;
	for(int i = 1; i <= n; i ++) {	
		scanf("%d", &a[i].x);
		a[i].idx = i;
		maxx = max(maxx, a[i].x);
		permt[a[i].x] ++;
	}

	for(int i = 1; i <= n; i ++) {
		if(vis[a[i].x]) continue;
		else vis[a[i].x] = true;
		for(int j = a[i].x; j <= maxx; j += a[i].x)
			cnt[j] += permt[a[i].x];	
	}


	for(int i = 1; i <= n; i ++)
		f[a[i].idx] = cnt[a[i].x] - 1;
		
	for(int i = 1; i <= n; i ++)
		if(i == n) printf("%d", f[i]);
		else printf("%d\n", f[i]);
}
发布了179 篇原创文章 · 获赞 1 · 访问量 7585

猜你喜欢

转载自blog.csdn.net/weixin_42596275/article/details/104330504