回 帖 发 新 帖 刷新版面

主题:如何使程序运行更快??

我做了一道acm的试题,题中需要用到递归的算法。但是递规很慢。题目要求是在1000ms结果我试的几次都是1015ms。多15ms,太郁闷了。请各位高手指点一下。怎么才能更快的运行。用栈操作是不是要比递归快呢?

回复列表 (共14个回复)

沙发

原题如下:

Description
Consider an arbitrary sequence of integers. One can place + or - operators between integers in the sequence, thus deriving different arithmetical expressions that evaluate to different values. Let us, for example, take the sequence: 17, 5, -21, 15. There are eight possible expressions: 17 + 5 + -21 + 15 = 16
17 + 5 + -21 - 15 = -14
17 + 5 - -21 + 15 = 58
17 + 5 - -21 - 15 = 28
17 - 5 + -21 + 15 = 6
17 - 5 + -21 - 15 = -24
17 - 5 - -21 + 15 = 48
17 - 5 - -21 - 15 = 18
We call the sequence of integers divisible by K if + or - operators can be placed between integers in the sequence in such way that resulting value is divisible by K. In the above example, the sequence is divisible by 7 (17+5+-21-15=-14) but is not divisible by 5.

You are to write a program that will determine divisibility of sequence of integers.


Input
The first line of the input file contains two integers, N and K (1 <= N <= 10000, 2 <= K <= 100) separated by a space.
The second line contains a sequence of N integers separated by spaces. Each integer is not greater than 10000 by it's absolute value.


Output
Write to the output file the word "Divisible" if given sequence of integers is divisible by K or "Not divisible" if it's not.

Sample Input

4 7
17 5 -21 15

Sample Output

Divisible

板凳

递归改成非递归的

3 楼

用循环

4 楼

你飞吧把机子冒烟都循环不玩 .....还是用栈吧,也许会快点我还没试过

5 楼

这个程序并不难,如果要速度快并不全是数据结构的问题,算法也很重要
这里的组合数不多,怎么可能要运行那么长的时间啊
你的代码发上来看看

6 楼

楼上,1 <= N <= 10000唉,不是只有4个

7 楼

9999个运算符显然不能搜索,太慢了
我的想法是把n个数Xn按照%k的余数分类,弄一个 m[k]数组来存每一个余数的次数就可以了
然后分析m[k]就很快了,比如m[0]可以忽略.m[i]可以跟自己抵消(减的时候),或者跟m[k-i]抵消(加的时候),等等
总之最后所有的都运算完了能全部抵消掉就是divisible

8 楼

两年前的东西大家还这么有热情~

9 楼

晕。。。不知道是哪位人兄顶起来的。。。

10 楼

帖子会不会跟酒一样?越陈越香?

我的感觉是,只怕不只多15ms,是超时了,谁知道会超多久~~

我来回复

您尚未登录,请登录后再回复。点此登录或注册