关于a-b数对的疑问
查看原帖
关于a-b数对的疑问
1259490
1continue1楼主2024/11/26 22:01

这个题我用纯二分超时了一个测试点 用map的话wa了三个测试点 有无大佬来指教一下问题啊

// 这道题的二分做法 
// 为什么会超时一个测试点呢???? 
// 92
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5 + 10;
int n,c;
map<int,int>mp;
int a[N];
int check(ll x)
{
	// 传入进来的答案就是x
	// 问你x是否能够达到呢?????
	// A = B + C;
	ll ans = 0;
	for(int i = 1;i<=n;i++)
	{
	    int temp = a[i] - c;
	    ans = ans + mp[temp];
	    if(ans>=x) break; 
	}
	if(ans>=x) return 1;
	else return 0;
}
void solve()
{
    cin >> n >> c;
	for(int i = 1;i<=n;i++) cin >> a[i];
    for(int i = 1;i<=n;i++) mp[a[i]]++;
    ll l = 0, r = 2e10+3e6;
    ll mid;
    while(l<r)
    {
    	mid = (l+r+1)/2;
    	int flag = check(mid);
    	if(flag)// 这样就是能达到的 
		l = mid; 
    	else
    	r = mid - 1;
	}
	cout << l << '\n';  	
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int t;
	//cin >> t;
	t = 1;
	while(t--) solve();
	return 0;
}
// 这个题的map的做法 
// 74
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
ll c;
const int N = 2e5 + 10;
ll a[N];
map<ll,ll>mp;
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cin >> n >> c;
	for(int i= 1;i<=n;i++) cin >> a[i];
	for(int i = 1;i<=n;i++) 
	{
		ll temp = a[i];
		mp[temp]++;
	}
	ll ans = 0;
	for(auto& k:mp)
	{
		// 然后开始遍历这个map
		// A = B + C;
		ll temp1 = k.second;
		ll h1 = k.first + c;
		ll h2 = k.first - c;
		if(h2>=0) ans = ans + mp[h2]*temp1;
		if(h1<=n) ans = ans + mp[h1]*temp1;
	}
	ans = ans/2; // 不能加重复了,所以要除2 
	cout << ans << '\n';
	return 0;
}
// 1 2 3
// 2 1 1
// 2 + 3 + 1  = 6
2024/11/26 22:01
加载中...