问题描述:
给定含有n个元素的多重集合S,每个元素在S中出现的次数称为该元素的重数。多重集S中重数最大的元素称为众数。
例如,S={1,2,2,2,3,5}。多重集S的众数是2,其重数为3。
编程任务:
对于给定的由n 个自然数组成的多重集S,编程计算S 的众数及其重数。
输入描述
第1行多重集S中元素个数n(n<=50000);接下来的n 行中,每行有一个自然数。
输出描述
输出文件有2 行,第1 行给出众数,第2 行是重数。(如果有多个众数,只输出最小的)
解题思路:
利用数组,其下标作为输入数据,其值作为这个数据的重复数量,代码如下
void write_data(unsigned int *p, unsigned int n)
{
unsigned int a(0);
while (n--){
std::cin >> a;
p[a] ++;
}
}
声明一个变量a,输入值赋值给a,将数组中第a个元素值+1
数据输入完成后,计算结果并输出
void proc_data(unsigned int *p, unsigned int n)
{
unsigned int ZongShu(0), ChongShu(0), i(0);
while (i<n){
if (ChongShu < p[i]){
ChongShu = p[i];
ZongShu = i;
}
i++;
}
std::cout << ZongShu << std::endl;
std::cout << ChongShu << std::endl;
}
主函数:
int main(void)
{
unsigned int NUM;
std::cin >> NUM;
unsigned int *p = new unsigned int[100000];
for (int i(0); i < 100000; i++)p[i] = 0;
write_data(p,NUM);
proc_data(p, 100000);
delete[] p;
system("pause");
return 0;
}
用到动态创建数组 new
function operator new[]
Allocate storage space for array
<类型> <指针变量> = new <类型> [<数组长度>]
// operator new[] example
#include <iostream> // std::cout
#include <new> // ::operator new[]
struct MyClass {
int data;
MyClass() {std::cout << '*';} // print an asterisk for each construction
};
int main () {
std::cout << "constructions (1): ";
// allocates and constructs five objects:
MyClass * p1 = new MyClass[5];
std::cout << '\n';
std::cout << "constructions (2): ";
// allocates and constructs five objects (nothrow):
MyClass * p2 = new (std::nothrow) MyClass[5];
std::cout << '\n';
delete[] p2;
delete[] p1;
return 0;
}