[哈希表] lg-P1102. A-B 数对(哈希表+双指针+模板题)

本文介绍了P1102A-B数对问题的解决策略,包括两种不同的解题方法。一种是使用哈希表快速查找,另一种是采用双指针技巧。作者指出在处理这类求解方案数的问题时,要注意可能的数值范围,以避免溢出。同时,文章提供了两种方法的代码实现,并讨论了它们的时间复杂度和常数因素。
摘要由CSDN通过智能技术生成

1. 题目来源

链接:P1102 A-B 数对

2. 题目解析

水题,题目不难,但是答案记得开 long long...............,要不一直 WA 一个点。这种求个数、求方案、且限制条件不够强的题目,一定要考虑最终的方案数是否很大。

题解区发现一位大佬使用双指针来做,也很不错,贴一下大佬的思路~

在这里插入图片描述
我在考虑能不能直接采用 lower_bound()、upper_bound() 代替这两个 while()…但貌似必然没有双指针的效果好,常数可能很大…甚至是 O(n)

代码:

// https://www.luogu.com.cn/problem/P1102

#include <iostream>
#include <unordered_map>
#include <algorithm>

using namespace std;

const int N = 2e5 + 5;

int n, c;
int a[N];
unordered_map<int, int> h;

int main() {
    scanf("%d%d", &n, &c);
    for (int i = 0; i < n; i ++ ) scanf("%d", &a[i]), h[a[i] - c] ++ ;
    
    long long res = 0;
    for (int i = 0; i < n; i ++ ) 
        if (h.count(a[i]))		// 不加这个也行,但哈希表会插入很多无效值
            res += h[a[i]];

    printf("%lld\n", res);
    return 0;
}

双指针大佬:

#include <bits/stdc++.h>
#define ll long long

using namespace std;

const int N = 2e5 + 10;
int n , c;
int a[N];

int main () 
{
	cin >> n >> c;
	for(int i = 1 ; i <= n ; i ++) cin >> a[i];
	sort(a + 1 , a + 1 + n);
	int l = 1, r1 = 1 , r2 = 1;
	ll ans = 0;
	for(l = 1 ; l <= n ; l ++) {
		while(r1 <= n && a[r1] - a[l] <= c) r1 ++;
		while(r2 <= n && a[r2] - a[l] < c ) r2 ++;
		if(a[r2] - a[l] == c && a[r1 - 1] - a[l] == c && r1 - 1 >= 1) 	
			ans += r1 - r2;
	}
	cout << ans;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ypuyu

如果帮助到你,可以请作者喝水~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值