procedure2012
It's not worth it to know you're not worth it!

[题目来源]:POJ1840

[关键字]:Hash

[题目大意]:给出形如:a1*x1^3+a2*x2^3+a3*x3^3+a4*x4^3+a5*x5^3=0的方程求其一共有多少解。

//===========================================================================================================

[分析]:原始得朴素思想是枚举前4个值然后判断,如果是解就加一。但如此必超时无疑,所以可以将其拆成两部分,要想成立必有前一部分的值等于后一部分的值的的相反数。枚举实际上就是把一部分的值和后一部分的每一个值比较查找符合条件的值。而要想加快就必须在查找上优化——Hash!先枚举下你两个x的值存入Hash表,再枚举后三个的值进行查找。

[代码]:

View Code
 1 program Project1;
2 var
3 a: array[0..10] of longint;
4 t: array[-50..50] of longint;
5 num: array[-20000..20000] of longint;
6 h: array[-20000..20000,0..20] of longint;
7
8 function hash(x: longint):longint;
9 begin
10 hash := x mod 15988;
11 end;
12
13 procedure init;
14 var
15 i: longint;
16 begin
17 for i := 1 to 5 do read(a[i]);
18 end;
19
20 procedure work;
21 var
22 i, j, k, i1, i2, i3, ans, tot: longint;
23 begin
24 tot := 0;
25 for i := -50 to 50 do
26 t[i] := i*i*i;
27 for i := -50 to 50 do
28 for j := -50 to 50 do
29 if (i <> 0) and (j <> 0) then
30 begin
31 ans := a[1]*t[i]+a[2]*t[j];
32 k := hash(ans);
33 //writeln(k);
34 inc(num[k]);
35 h[k,num[k]] := ans;
36 end;
37 for i1 := -50 to 50 do
38 for i2 := -50 to 50 do
39 for i3 := -50 to 50 do
40 if (i1 <> 0) and (i2 <> 0) and (i3 <> 0) then
41 begin
42 ans := a[3]*t[i1]+a[4]*t[i2]+a[5]*t[i3];
43 ans := -ans;
44 k := hash(ans);
45 for j := 1 to num[k] do
46 if h[k,j] = ans then inc(tot);
47 end;
48 writeln(tot);
49 end;
50
51 begin
52 init;
53 work;
54 end.

posted on 2011-10-18 18:39  procedure2012  阅读(314)  评论(0编辑  收藏  举报