请教一个Time Limit Exceed的问题,关于ACM的。

carlblack1987 2015-07-18 05:33:19
一个挺简单的题目,但是始终是报Time Limit Exceed的问题,
麻烦大家给看看哪里可以改进下算法。

题目:
Description
One day,Little-Y saw many numbers standing in a row. A question suddenly appeared in her mind, ”From the L-th number to the R-th number, how many of them is a mutiple of P ? (P is a prime number) , and how quickly can I settle this problem ? ”

Input
Mutiple test cases. Please process till the end of file.
For each test case:
The first line contains two positive integers n and q (1<=n,q<=10^5), which means there are n integers standing in a row and q queries followed.
The second line contains n positive integers, a1,a2,a3,…,an (no more than 10^6) . Here, ai means the i-th integer in the row.
The next are q queries, each of which takes one line. For each query, there are three integers L,R,P (1<=L<=R<=n, 1<=P<=10^6, P is gurantteed to be a prime number). Their meanings have been mentioned in the discription.


Output
For each query, output the answer in one line.

Sample Input
6 5
12 8 17 15 90 28
1 4 3
2 6 5
1 1 2
3 5 17
1 6 999983

Sample Output
2
2
1
1
0



我的解答:

#include "stdafx.h"
#include <iostream>
#include <map>
using namespace std;

int main(int argc, char* argv[])
{
int elemNum, queryNum;
int i, j, z, son, answer, L, R, P;
while(cin>>elemNum>>queryNum) {
int *elemList = new int[elemNum];
while(elemNum --)
cin>>elemList[elemNum];

int (*queryList)[3] = new int[queryNum][3];

while(queryNum --) {
cin>>queryList[queryNum][0];
cin>>queryList[queryNum][1];
cin>>queryList[queryNum][2];

answer = 0;
son = queryList[queryNum][2];
for(i = queryList[queryNum][0] - 1;i < queryList[queryNum][1];i ++) {
elemList[i] % son == 0 ? answer ++ : answer;
}
cout<<answer<<endl;
}

}
return 0;
...全文
516 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
brookmill 2015-07-19
  • 打赏
  • 举报
回复
引用 3 楼 carlblack1987 的回复:
[quote=引用 2 楼 brookmill 的回复:] 刚才忘了说,打表需要额外的内存。这道题没说内存限制是多少,不知道会不会超了
感谢回复!!! 这道题的内存限制是128MB,时间限制是1秒。 你说的这个方法我会试试,你的意思是先用容器将每个数字的因数都装进去,然后运算的时候直接去检索就行了么?[/quote] 128M应该够用了。 题目说了所有的P都是质数,所以容器里装“质因数”就可以了,应该比“因数”快一点。 比如12,只有2和3,4和6就不用了。
carlblack1987 2015-07-18
  • 打赏
  • 举报
回复
引用 2 楼 brookmill 的回复:
刚才忘了说,打表需要额外的内存。这道题没说内存限制是多少,不知道会不会超了
感谢回复!!! 这道题的内存限制是128MB,时间限制是1秒。 你说的这个方法我会试试,你的意思是先用容器将每个数字的因数都装进去,然后运算的时候直接去检索就行了么?
brookmill 2015-07-18
  • 打赏
  • 举报
回复
刚才忘了说,打表需要额外的内存。这道题没说内存限制是多少,不知道会不会超了
brookmill 2015-07-18
  • 打赏
  • 举报
回复
对于ACM超时,经常可以用打表的方法来提高速度。具体到这道题: 第一步:首先把10^6以内的所有质数找出来,用筛法很快。ACM里面用到质数表的题目非常多,写一次以后经常可以重复利用。 第二步:把读入的所有a1~an分解质因数,每个ai的结果各自保存,可以考虑用set这样查询很快。 第三步:剩下的查询就简单了。因为题目保证了所有的P都是质数,只要找一下每个质数在多少个ai的质因数表里面出现就行了。 这道题的查询最多只有10000次,所以效果未必很明显。如果是海量查询效率应该会提高很多,因为可以少做很多除法。

64,282

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧