HDU-1280(哈希表求法)

本文介绍了一种通过哈希映射实现的算法,用于找出数组中所有可能的两数之和中前M大的数。该算法首先计算数组中所有不同两数组合的和,并将这些和存入哈希映射中进行计数。然后遍历哈希映射找到最大的M个数并输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目名称:前m大的数  
题目链接:https://vjudge.net/problem/HDU-1280
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define getHassVal(i, j) arr[i] + arr[j]

using namespace std;
const int MAXN = 1500000;
int arr[5000];
int hashMap[MAXN];

int main()
{
    int n, m;
    while(scanf("%d%d", &n, &m) != EOF)
    {
        memset(hashMap, 0, sizeof(hashMap));
        for(int i = 0; i < n; ++i) cin >> arr[i];
        for(int i = 0; i < n; ++i)
            for(int j = i + 1; j < n; ++j) hashMap[getHassVal(i, j)]++;

        int flag = 0;
        for(int i = MAXN - 1; i > 0&&m>0; )
        {
            if(hashMap[i] == 0){i--; continue;}
            if(flag) cout << ' ' << i;
            else cout << i;
            flag = 1;
            hashMap[i]--;
            m--;
        }
        cout << endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值