[分治算法]众数问题

众数问题

http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Contest/contestproblem/cid/3015/pid/1710.html

Time Limit: 2000 ms Memory Limit: 65536 KiB
 

Problem Description

给定含有n个元素的多重集合S,每个元素在S中出现的次数称为该元素的重数。多重集S中重数最大的元素称为众数。例如,S={1,2,2,2,3,5}。多重集S的众数是2,其重数为3。对于给定的由n 个自然数组成的多重集S,计算S的众数及其重数。如果出现多个众数,请输出最小的那个。

Input

输入数据的第1行是多重集S中元素个数n(n<1300000);接下来的n行中,每行有一个最多含有5位数字的自然数,。

Output

输出数据的第1行给出众数,第2行是重数。

Sample Input

6
1
2
2
2
3
5

Sample Output

2
3

解决思路:

使用数组Arr[i],其中i表示输入数据,Arr[i]表示i出现的个数。第一次循环输入并找出众数,而二次循环判断i,找到最小的。

注意事项:

因为 索引i 与 Arr[i] 之间存在对应关系,此时如果调用Sort[i] 会破坏这种对应关系。另一种解决方法是使用 Arr[t[i]],对t[i]使用Sort()排序。


源代码:

 1 #include <iostream>
 2 #include <algorithm>
 3 using namespace std;
 4 int arr[100005] = { 0 };
 5 
 6 bool cmp(int i, int j) {
 7     return i > j;
 8 }
 9 int main()
10 {
11     int Count = 0;
12     int MostElem = 0;
13     int num;
14     int Elem;
15 
16     std::cin >> num;
17     
18 
19     // 先输入并计算
20     for (int i = 0; i < num; i++) {
21         std::cin >> Elem;
22         arr[Elem]++;
23         if (arr[Elem] > Count) {
24             Count = arr[Elem];
25         }
26     }
27 
28     // 若直接调用sort,则会破坏 i 与 arr[i] 之间的对应关系。
29     // 直接再从头遍历一遍
30     int temp = 100000;
31     for (int i = 0; i < 100000; i++) {
32         if (arr[i] == Count && i < temp){
33             temp = i;
34         }
35     }
36 
37     // 直接输出
38     cout << temp << endl << Count << endl;
39 
40 
41     return 0;
42 }

猜你喜欢

转载自www.cnblogs.com/onetrainee/p/11665466.html