水果购物问题:最小和最大总价 - 算法分析
水果购物问题:最小和最大总价 - 算法分析/n/nThe spring is coming and it means that a lot of fruits appear on the counters. One sunny day little boy Valera decided to go shopping. He made a list of 'm' fruits he wanted to buy. If Valera want to buy more than one fruit of some kind, he includes it into the list several times./n/nWhen he came to the fruit stall of Ashot, he saw that the seller hadn't distributed price tags to the goods, but put all price tags on the counter. Later Ashot will attach every price tag to some kind of fruits, and Valera will be able to count the total price of all fruits from his list. But Valera wants to know now what can be the smallest total price (in case of the most 'lucky' for him distribution of price tags) and the largest total price (in case of the most 'unlucky' for him distribution of price tags)./n/n### 输入格式/n/nThe first line of the input contains two integer number 'n' and 'm' ( 1<=n,m<=100 ) — the number of price tags (which is equal to the number of different kinds of fruits that Ashot sells) and the number of items in Valera's list. The second line contains 'n' space-separated positive integer numbers. Each of them doesn't exceed 100 and stands for the price of one fruit of some kind. The following 'm' lines contain names of the fruits from the list. Each name is a non-empty string of small Latin letters which length doesn't exceed 32. It is guaranteed that the number of distinct fruits from the list is less of equal to 'n'. Also it is known that the seller has in stock all fruits that Valera wants to buy./n/n### 输出格式/n/nPrint two numbers 'a' and 'b' ( a<=b ) — the minimum and the maximum possible sum which Valera may need to buy all fruits from his list./n/n### 算法1/n/n**(哈希表) $O(m)$/n/n首先读入每种水果的价格,然后将其存储在哈希表中,键为水果名,值为价格。/n/n然后遍历Valera的购物清单,将每种水果的价格累加起来,即可得到购物清单的总价。/n/n为了求最小和最大总价,需要对哈希表中的价格按照从小到大排序,然后依次将最小的价格分配给购物清单中每种水果,将最大的价格分配给购物清单中数量最多的水果。/n/n#### 时间复杂度/n/n读入价格需要 $O(n)$ 的时间,遍历购物清单需要 $O(m)$ 的时间,排序需要 $O(n /log n)$ 的时间,分配价格需要 $O(m)$ 的时间,因此总时间复杂度为 $O(n /log n + m)$。/n/n#### 空间复杂度/n/n哈希表所需空间为 $O(n)$,因此总空间复杂度为 $O(n)$。/n/n#### C++ 代码/n/nc++/n// C++ 代码示例/n/n/n### 算法2/n/n(计数排序) $O(n+m)$**/n/n由于价格不超过100,可以使用计数排序。首先读入每种水果的价格,然后将其存储在计数数组中,下标为价格,值为该价格的水果种类数量。然后遍历Valera的购物清单,将每种水果的价格累加起来,即可得到购物清单的总价。为了求最小和最大总价,需要从计数数组中依次取出最小的价格和最大的价格,然后依次将最小的价格分配给购物清单中每种水果,将最大的价格分配给购物清单中数量最多的水果。/n/n#### 时间复杂度/n/n读入价格需要 $O(n)$ 的时间,遍历购物清单需要 $O(m)$ 的时间,计数排序需要 $O(n)$ 的时间,分配价格需要 $O(m)$ 的时间,因此总时间复杂度为 $O(n+m)$。/n/n#### 空间复杂度/n/n计数数组所需空间为 $O(100)$,因此总空间复杂度为 $O(1)$。/n/n#### C++ 代码/n/nc++/n// C++ 代码示例/n/n
原文地址: https://www.cveoy.top/t/topic/nP9A 著作权归作者所有。请勿转载和采集!