TopCoder SRM 399 Level 2 1000
http://www.topcoder.com/stat?c=problem_statement&pm=8758&rd=12171
给定N和一个整数集合a,用不属于a的3个整数相乘得出离N最近的整数
N的范围1~1000
从小到大3重循环就可以解
理论上的复杂度高达1000^3
如果确实算一次我的电脑要跑到6秒
不过其实当乘积减去N已经超过之前的差额时就可以break了
所以计算量其实很小
加上break算一次只要零点零几秒
另外的陷阱是循环如果只是1~1000是不行的
有可能会用到比1000还大的因子
http://www.topcoder.com/stat?c=problem_statement&pm=8758&rd=12171
给定N和一个整数集合a,用不属于a的3个整数相乘得出离N最近的整数
N的范围1~1000
从小到大3重循环就可以解
理论上的复杂度高达1000^3
如果确实算一次我的电脑要跑到6秒
不过其实当乘积减去N已经超过之前的差额时就可以break了
所以计算量其实很小
加上break算一次只要零点零几秒
另外的陷阱是循环如果只是1~1000是不行的
有可能会用到比1000还大的因子
1
import
java.util.
*
;
2
import
java.util.regex.
*
;
3
import
java.text.
*
;
4
import
java.math.
*
;
5
import
java.awt.geom.
*
;
6![]()
7
public
class
AvoidingProduct
8![]()
{
9
int SIZE = 1101;
10
11
public int[] getTriple(int[] a, int n)
12![]()
{
13
boolean[] table = new boolean[SIZE];
14
Arrays.fill(table, true);
15
for(int i = 0 ; i < a.length ; ++ i)
16
table[a[i]] = false;
17
int x,y,z;
18
int[] ans = new int[3];
19
Arrays.fill(ans, Integer.MAX_VALUE);
20
int gap = Integer.MAX_VALUE;
21
Outer:
22![]()
for(x = 1 ; x < SIZE; ++ x)
{
23
if(table[x] == false) continue;
24![]()
for(y = 1; y < SIZE; ++ y)
{
25
if(table[y] == false) continue;
26![]()
for(z = 1 ; z < SIZE; ++ z)
{
27
if(table[z] == false) continue;
28
int total = x * y * z;
29
int sub = n - total;
30![]()
if(Math.abs(sub) < gap)
{
31
ans[0] = x; ans[1] = y; ans[2] = z;
32
gap = Math.abs(sub);
33
}
34
if(sub < 0 && Math.abs(sub) >= gap)
35
break ;
36
}
37
}
38
}
39
return ans;
40
}
41
42
}
2
3
4
5
6
7
8

9
10
11
12

13
14
15
16
17
18
19
20
21
22

23
24

25
26

27
28
29
30

31
32
33
34
35
36
37
38
39
40
41
42