Problem 1582 众数问题 from http://acm.fzu.edu.cn/problem.php?pid=1582

来源:互联网 发布:查士丁尼瘟疫 知乎 编辑:程序博客网 时间:2024/05/01 18:42

 Problem Description

给定含有n个元素的多重集合S,每个元素在S中出现的次数称为该元素的重数。多重集S中重数最大的元素称为众数。

例如,S={1,2,2,2,3,5}。

多重集S的众数是2,其重数为3。

 Input

输入包括多组数据,请处理到EOF结束。

每组数据,以一个n(1<=n<=100,000)开始,接下n行,每行有一个数字(-231~231)。

 Output

对于每组输入数据,输出一行一个数字,表示众数。如果存在多个解,只需输出值最小的众数即可。

 Sample Input

61222353-1-1-1

 Sample Output

2-1

 Source

FOJ月赛-2008年4月

这种思路还可以应用在求最小差上面

[cpp] view plaincopy
  1. #include<cstdio>  
  2. #include<iostream>  
  3. #include<algorithm>  
  4. #include<cstring>  
  5. #include<map>  
  6. using namespace std;  
  7. int a[100000];  
  8. int main(){  
  9.     int n, t, max, val;  
  10.     //freopen("in.txt", "r", stdin);  
  11.     while(scanf("%d", &n)!=EOF){  
  12.   
  13.         for(int i=0;i<n;++i)  
  14.             scanf("%d", a+i);  
  15.         sort(a, a+n);  
  16.         int pre = a[0];  
  17.         int count = 1, max = 1, val=pre;  
  18.         for(int i=1;i<n;++i){  
  19.             if(a[i] == pre)  
  20.                 count++;  
  21.             else{  
  22.                 pre = a[i];  
  23.                 count = 1;  
  24.             }  
  25.             if(max<count){  
  26.                 max = count;  
  27.                 val = a[i];  
  28.             }  
  29.         }  
  30.         printf("%d\n", val);  
  31.   
  32.     }  
  33.   
  34.    //fclose(stdin);  
  35.   
  36. }  
原创粉丝点击