标签:through ecif 独立 相对 set 中位数 eterm log rmi
**小白一枚,欢迎指教
Question:
You are interested in analyzing some hard-to-obtain data from two separate databases. Each
database contains n numerical values, so there are 2n values total and you may assume that no
two values are the same. You‘d like to determine the median of this set of 2n values, which we
will dene here to be the nth smallest value.
However, the only way you can access these values is through queries to the databases. In
a single query, you can specify a value k to one of the two databases, and the chosen database
will return the kth smallest value that it contains. Since queries are expensive, you would like
to compute the median using as few queries as possible.
Give an algorithm that nds the median value using at most O(log n) queries.
分析:
记两个数据库为DB1与DB2,各存储了n个数,每次从数据库中查询返回的结果值记为k1与k2。
先取DB1的最大值(k1)与DB2最小值(k2)进行判断,若k1<k2,则k1即为中位值,反之亦然。
否则,分别取DB1与DB2的第n/2小的值进行比较,若 k1与k2相等,则这个值为中位数,若k1大于k2,则继续取DB1第 n/4的值与DB2第 3n/4的值进行比较,反之亦然,依次类推,当不能再分时,相对小的那一方为两个独立数据库DB1与DB2的中间值。
伪代码:
1 k1←n/2 2 k2←n/2 3 Function getMedNum(DB1,DB2,k1,k2,n) 4 If get(DB1,n)<get(DB2,1) then 5 Return get(DB1,n) 6 elseIf get(DB2,n)<get(DB1,1) then 7 Return get(DB2,n) 8 End if 9 Num1←get(DB1,k1) 10 Num2←get(DB2,k2) 11 If min(k1,k2)<2 then 12 Return k1<k2?k1:k2 13 End if 14 If Num1=Num2 then 15 Return Num1 16 elseIf Num1>Num2 then 17 getMedNum(DB1,DB2,k1/2,(k2+n)/2) 18 elseIf Num2>Num1 then 19 getMedNum(DB1,DB2, (k1+n)/2,k2/2) 20 End if 21 End function
标签:through ecif 独立 相对 set 中位数 eterm log rmi
原文地址:http://www.cnblogs.com/babetterdj/p/7740091.html