合并序列
有两个长度为N的序列A和B,在A和B中各任取一个数相加可以得到N^2个和,求这N^2个和中最小的N个。
把a,b数组排序后,用pos[i]表示当前与a[i]取得未取最小值的b[j]的编号j,也就是说
pos[i]=k{a[i]+b[k]-->min}
每次取min{a[i]+b[pos[i]]}输出,再将pos[i]加一即可,这个算法是n^2的,
进一步思考,取一堆数中的最小值,可以用堆维护,nlogn
View Code
1 {为方便heap中存编号而不是具体值}
2 program sequence(input,output);
3 var
4 a,b,pos : array[0..200000] of longint;
5 heap : array[0..200000] of longint;
6 n,tot : longint;
7 procedure swap(var aa,bb: longint );
8 var
9 tt : longint;
10 begin
11 tt:=aa;
12 aa:=bb;
13 bb:=tt;
14 end; { swap }
15 procedure insect(poss :longint );
16 var
17 now : longint;
18 begin
19 inc(tot);
20 heap[tot]:=poss;
21 now:=tot;
22 while (now<>1)and(a[heap[now]]+b[pos[heap[now]]]<a[heap[now>>1]]+b[pos[heap[now>>1]]]) do
23 begin
24 swap(heap[now],heap[now>>1]);
25 now:=now>>1;
26 end;
27 end; { insect }
28 procedure down(poss: longint );
29 var
30 now : longint;
31 begin
32 now:=poss;
33 while (now<tot)and((a[heap[now]]+b[pos[heap[now]]]>a[heap[now<<1]]+b[pos[heap[now<<1]]])or(a[heap[now]]+b[pos[heap[now]]]>a[heap[now*2+1]]+b[pos[heap[now*2+1]]])) do
34 begin
35 if a[heap[now*2]]+b[pos[heap[now*2]]]<a[heap[now*2+1]]+b[pos[heap[now*2+1]]] then
36 begin
37 swap(heap[now],heap[now*2]);
38 now:=now*2;
39 end
40 else
41 begin
42 swap(heap[now],heap[now*2+1]);
43 now:=now*2+1;
44 end;
45 end;
46 end; { down }
47 procedure sort1(p,q :longint );
48 var
49 i,j,m : longint;
50 begin
51 i:=p;
52 j:=q;
53 m:=a[(i+j)>>1];
54 repeat
55 while a[i]<m do
56 inc(i);
57 while a[j]>m do
58 dec(j);
59 if i<=j then
60 begin
61 swap(a[i],a[j]);
62 inc(i);
63 dec(j);
64 end;
65 until i>j;
66 if i<q then sort1(i,q);
67 if j>p then sort1(p,j);
68 end; { sort1 }
69 procedure sort2(p,q :longint );
70 var
71 i,j,m : longint;
72 begin
73 i:=p;
74 j:=q;
75 m:=b[(i+j)>>1];
76 repeat
77 while b[i]<m do
78 inc(i);
79 while b[j]>m do
80 dec(j);
81 if i<=j then
82 begin
83 swap(b[i],b[j]);
84 inc(i);
85 dec(j);
86 end;
87 until i>j;
88 if i<q then sort2(i,q);
89 if j>p then sort2(p,j);
90 end; { sort2 }
91 procedure main;
92 var
93 i : longint;
94 begin
95 readln(n);
96 fillchar(a,sizeof(a),63);
97 fillchar(b,sizeof(b),63);
98 for i:=1 to n do
99 read(a[i]);
100 readln;
101 for i:=1 to n do
102 read(b[i]);
103 readln;
104 for i:=1 to n do
105 pos[i]:=1;
106 tot:=0;
107 sort1(1,n);
108 sort2(1,n);
109 for i:=1 to n do
110 insect(i);
111 for i:=1 to n do
112 begin
113 write(a[heap[1]]+b[pos[heap[1]]],' ');
114 inc(pos[heap[1]]);
115 down(1);
116 end;
117 end; { main }
118 begin
119 assign(input,'sequence.in');reset(input);
120 assign(output,'sequence.out');rewrite(output);
121 main;
122 close(input);
123 close(output);
124 end.