hash的简单应用

来源:互联网 发布:node.js 安装 编辑:程序博客网 时间:2024/04/20 19:20

*1
题目描述: 读入N名学生的成绩,将获得某一给定分数的学生人数输出
输入: 测试输入包含若干测试用例,每个测试用例的格式为:
第1行:N
第2行:N名学生的成绩,相邻两数字用一个空格间隔
第3行:给定分数
当读到N=0时输入结束,其中N不超过1000,成绩分数为(包含)0到100之间的一个整数
输出: 对每个测试用例,将获得给定分数的学生人数输出

#include <iostream>using namespace std;int main(){    int N;    int score1;    int score[101] = { 0 };    while (cin >> N)    {        for (int i = 0; i < N; i++)        {            cin >> score1;            score[score1]++;        }        int testscore;        cin >> testscore;        cout << score[testscore] << endl;    }    system("pause");    return 0;}

*
题目描述: 给你n个整数,轻按从大到小的顺序输出其中前m大的数
输入: 每组测试数据有两行,第一行有两个数n,m(0<n,m<1000000),第二行包含n个各不相同,且都处于区间[-500000,500000]的整数。
输出: 对每组测试数据从大到小的顺序输出前m大的数

#include <iostream>#include <stdio.h>using namespace std;int Hash[1000001];                            //Hash首字母要大写#define OFFECT 500000int main(){//    int OFFECT = 5000;                        //半数据区间    int n, m;    while (cin >> n >> m)    {        for (int i = 0; i < 2*OFFECT; i++)            Hash[i] = 0;//        int hash[10001] = { 0 };            //对读进去的数进行相应的计数        int *num = new int[n];                //存放前m大的数,其中使用n,主要是因为考虑到一个数可能会出现多次时,后面进行计数使用m可能会出现溢出        for (int i = 0; i < n; i++)        {            int num;            cin >> num;            Hash[num + OFFECT]++;            //数据所处的区间为[-5000,5000]        }        int no = 0;        for (int i = 2*OFFECT; i >= 0; i--)        {            if (Hash[i] != 0)            {                if (no < m)                {                    for (int j = no; j < no + Hash[i]; j++)            //注意j的初始值为no,存放在一个数组中                        num[j] = i - OFFECT;                    no += Hash[i];            //no计数                }                else                    break;            }        }        for (int i = 0; i < m; i++)            cout << num[i] << " ";        cout << endl;    }    system("pause");    return 0;}
0 0
原创粉丝点击