chapter 2.getting started

2-1 Insertion sort on small arrays in merge sort
Although merge sort runs in(n lg n) worst-case time and insertion sort runs
in(n^2) worst-case time, the constant factors in insertion sort make it faster for
small n. Thus, it makes sense to use insertion sort within merge sort when subprob-
lems become sufficiently small. Consider a modification to merge sort in which
n/k sublists of length k are sorted using insertion sort and then merged using the
standard merging mechanism, where k is a value to be determined.
a. Show that the n/k sublists, each of length k, can be sorted by insertion sort in(nk) worst-case time.

b. Show that the sublists can be merged in (n lg(n/k)) worst-case time.
c. Given that the modified algorithm runs in (nk + n lg(n/k)) worst-case time,
what is the largest asymptotic (-notation) value of k as a function of n for
which the modified algorithm has the same asymptotic running time as standard
merge sort?

大概的话是k<lgn
d. How should k be chosen in practice? 

这个优化在实际应用中还是很有效的,比如tyvj(P1038) :

        老管家是一个聪明能干的人。他为财主工作了整整10年,财主为了让自已账目更加清楚。要求管家每天记k次账,由于管家聪明能干,因而管家总是让财主十分满意。但是由于一些人的挑拨,财主还是对管家产生了怀疑。于是他决定用一种特别的方法来判断管家的忠诚,他把每次的账目按1,2,3…编号,然后不定时的问管家问题,问题是这样的:在a到b号账中最少的一笔是多少?为了让管家没时间作假他总是一次问多个问题。

输入格式 Input Format
输入中第一行有两个数m,n表示有m(m<=100000)笔账,n表示有n个问题,n<=100000。
第二行为m个数,分别是账目的钱数
后面n行分别是n个问题,每行有2个数字说明开始结束的账目编号。


输出格式 Output Format
输出文件中为每个问题的答案。具体查看样例。

样例输入 Sample Input 

10 3
1 2 3 4 5 6 7 8 9 10
2 7
3 9
1 10 

样例输出 Sample Output

2 3 1

不做优化的话:

 1 const mm=100000;
2 var m,n,i,l,r:longint;
3 a:array[1..mm] of longint;
4 function min(x,y:longint):longint;
5 begin
6 if a[x]>a[y] then exit(y)
7 else exit(x);
8 end;
9 function find(l,r:longint):longint;
10 begin
11 if l=r then exit(l)
12 else
13 if l>r then exit(mm+1)
14 else
15 exit(min(find(l,(l+r) div 2),find((l+r) div 2+1,r)));
16 end;
17 begin
18 readln(m,n);
19 for i:=1 to m do read(a[i]);
20 for i:=1 to n do
21 begin
22 readln(l,r);
23 write(find(l,r),' ');
24 end;
25 end.
稍作优化(第15,16行)

 1 const mm=100000;
2 var m,n,i,l,r:longint;
3 a:array[1..mm] of longint;
4 function min(x,y:longint):longint;
5 begin
6 if a[x]>a[y] then exit(y)
7 else exit(x);
8 end;
9 function find(l,r:longint):longint;
10 begin
11 if l=r then exit(l)
12 else
13 if l>r then exit(mm+1)
14 else
15 if r-l=1 then exit(min(l,r))
16 else
17 exit(min(find(l,(l+r) div 2),find((l+r) div 2+1,r)));
18 end;
19 begin
20 assign(input,'input.in');reset(input);
21 assign(output,'output.out');rewrite(output);
22 readln(m,n);
23 for i:=1 to m do read(a[i]);
24 for i:=1 to n do
25 begin
26 readln(l,r);
27 write(a[find(l,r)],' ');
28 end;
29 close(input);close(output);
30 end.






 

posted @ 2011-09-05 08:47  Mose  阅读(267)  评论(0编辑  收藏  举报