hdu2578 Dating with girls(1) (二分 || map)

本文通过一个具体的编程问题,对比了二分查找与Map查找两种算法的执行效率。结果显示,在特定的数据集上,二分查找的运行时间显著优于Map查找。

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

题目链接:点击打开链接


在这题中使用二分查找比使用map查找更快


二分查找法代码如下(625ms):

#include <cstdio>
#include <algorithm>
using namespace std;

const int N = 111111;
int a[N];

int main()
{
    int t, n, *m, k, cnt, f;
    scanf("%d", &t);
    while(t-- && scanf("%d%d", &n, &k)) {
        cnt = 0, f = 0;
        for(int i = 0; i < n; i++) scanf("%d", a + i);
        sort(a, a + n);
        m = unique(a, a + n);
        for(int i = 0; i < m - a; i++) {
            if(a[i] << 1 > k) break;
            if(binary_search(a, m, k - a[i])) {
                if(a[i] << 1 == k) f = 1;
                cnt++;
            }
        }
        cnt <<= 1;
        printf("%d\n", f ? cnt - 1 : cnt);
    }
    return 0;
}

map查找法代码如下(1390ms):

#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;

const int N = 111111;
int a[N];
map<int, int> m;

int main()
{
    int t, n, k, f, cnt;
    scanf("%d", &t);
    while(t-- && scanf("%d%d", &n, &k)) {
        m.clear();
        cnt = 0, f = 0;
        for(int i = 0; i < n; i++) {
            scanf("%d", a + i);
            m[a[i]] = 1;
        }
        sort(a, a + n);
        int l = unique(a, a + n) - a;
        for(int i = 0; i < l; i++) {
            if(a[i] << 1 > k) break;
            if(m[k - a[i]]) {
                if(a[i] << 1 == k) f = 1;
                cnt++;
            }
        }
        cnt <<= 1;
        printf("%d\n", f ? cnt - 1 : cnt);
    }
    return 0;
}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值