pku1338 Ugly Numbers

把质因子只有2,3,5的数称为Ugly数,求第k大的Ugly数。(1是第一个)

用堆保存数字,开始堆中只有1,每次删除最小值,把最小值的2倍,3倍,5倍插入到堆中,执行k次就得到结果。

注意要判重,用个hash就行,有点羡慕C++的map了。

View Code
  1 program pku1338(input,output);
2 type
3 longint = int64;
4 node = ^link;
5 link = record
6 worth : longint;
7 next : node;
8 end;
9 var
10 heap : array[0..10000] of longint;
11 hash : array[0..65537] of node;
12 n,tot : longint;
13 answer : longint;
14 procedure swap(var aa,bb: longint );
15 var
16 tt : longint;
17 begin
18 tt:=aa;
19 aa:=bb;
20 bb:=tt;
21 end; { swap }
22 function find(x :longint ):boolean;
23 var
24 t : node;
25 begin
26 t:=hash[x mod 65537];
27 while t<>nil do
28 begin
29 if t^.worth=x then
30 exit(true);
31 t:=t^.next;
32 end;
33 exit(false);
34 end; { find }
35 procedure inn(x :longint );
36 var
37 t : node;
38 begin
39 new(t);
40 t^.worth:=x;
41 t^.next:=hash[x mod 65537];
42 hash[x mod 65537]:=t;
43 end; { inn }
44 procedure up(x: longint );
45 begin
46 while (heap[x]<heap[x>>1])and(x<>1) do
47 begin
48 swap(heap[x],heap[x>>1]);
49 x:=x>>1;
50 end;
51 end; { up }
52 procedure down(x :longint );
53 begin
54 while (x*2<=tot)and((heap[x]>heap[x*2])or(heap[x]>heap[x*2+1])) do
55 begin
56 if heap[x<<1]>heap[x*2+1] then
57 begin
58 swap(heap[x],heap[x*2+1]);
59 x:=x*2+1;
60 end
61 else
62 begin
63 swap(heap[x],heap[x*2]);
64 x:=x<<1;
65 end;
66 end;
67 end; { down }
68 procedure insect(x :longint );
69 begin
70 inc(tot);
71 heap[tot]:=x;
72 up(tot);
73 end; { insect }
74 function delete():longint;
75 begin
76 delete:=heap[1];
77 swap(heap[1],heap[tot]);
78 heap[tot]:=maxlongint>>1;
79 dec(tot);
80 down(1);
81 end; { delete }
82 procedure main;
83 var
84 i : dword;
85 begin
86 fillchar(heap,sizeof(heap),63);
87 for i:=1 to 65537 do
88 hash[i]:=nil;
89 answer:=1;
90 tot:=1;
91 heap[1]:=1;
92 inn(1);
93 for i:=1 to n do
94 begin
95 answer:=delete();
96 if not find(answer*2) then
97 begin
98 inn(answer*2);
99 insect(answer*2);
100 end;
101 if not find(answer*3) then
102 begin
103 inn(answer*3);
104 insect(answer*3);
105 end;
106 if not find(answer*5) then
107 begin
108 inn(answer*5);
109 insect(answer*5);
110 end;
111 end;
112 writeln(answer);
113 end; { main }
114 begin
115 readln(n);
116 while n<>0 do
117 begin
118 main;
119 readln(n);
120 end;
121 end.



posted @ 2012-03-18 17:11  Codinginging  阅读(563)  评论(0编辑  收藏  举报