二分法做题记录
丢瓶盖
题:
陶陶是个贪玩的孩子,他在地上丢了A个瓶盖,为了简化问题,我们可以当作这A个瓶盖丢在一条直线上,现在他想从这些瓶盖里找出B个,使得距离最近的2个距离最大,他想知道,最大可以到多少呢?
输入格式
第一行,两个整数,A,B(2≤B≤A≤10^5)。
第二行,A个整数,分别为这A个瓶盖坐标,在[1,10^9]范围内。
输出格式
仅一个整数,为所求答案。
Sample Input
5 3
1 2 3 4 5
Sample Output
2
思路:
二分法
首先,排序,然后固定选第一个瓶盖。
由题知,B大于等于二,可以用二分法取中间距离,一直二分距离,直到找到可以满足如题条件的距离,然后在上个二分点和当前二分点之间继续二分寻找最大距离。
ps:我以为这题是道思维题,再加上好久没用过二分法了,根本没往这方面想orz
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N = 1e5 + 5;
ll p[N];
ll a, b, i, mid;
bool check(ll x)
{
//检查是否满足能找出b个元素相邻距离大于等于当前的最大距离
ll countnum = 1 , last = 1;
for(i = 2; i <= a; ++i)
{
if(p[i] - p[last] >= x)
{
countnum++;
last = i;
}
}
if(countnum >= b)
return true;
else
return false;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> a >> b;
for(i = 1; i <= a ; ++i)
cin >> p[i];
sort(p + 1, p + 1 + a);
ll r = p[a]-p[1];
ll l = 0;
//如果满足check(mid),在上一个二分点和当前二分点继续寻找最大距离
//如果不满足,就一直二分缩小距离区间
while(l < r)
{
mid = (l + r + 1) >> 1;
if(check(mid))
l = mid;
else
r = mid - 1;
}
cout << l << endl;
return 0;
}
Number of Pairs
题:
You are given an array a of n integers. Find the number of pairs (i,j) (1≤i<j≤n) where the sum of ai+aj is greater than or equal to l and less than or equal to r (that is, l≤ai+aj≤r).
For example, if n=3, a=[5,1,2], l=4 and r=7, then two pairs are suitable:
i=1 and j=2 (4≤5+1≤7);
i=1 and j=3 (4≤5+2≤7).
Input
The first line contains an integer t (1≤t≤10^4). Then t test cases follow.
The first line of each test case contains three integers n,l,r (1≤n≤2⋅10^5, 1≤l≤r≤10^9) — the length of the array and the limits on the sum in the pair.
The second line contains n integers a1,a2,…,an (1≤ai≤10^9).
It is guaranteed that the sum of n overall test cases does not exceed 2⋅10^5.
Output
For each test case, output a single integer — the number of index pairs (i,j) (i<j), such that l≤ai+aj≤r.
Example
input
4
3 4 7
5 1 2
5 5 8
5 1 2 4 3
4 100 1000
1 1 1 1
5 9 13
2 5 5 1 1
output
2
7
0
1
题意:
给出n个元素的数组a,给定l,r,l <= ai + aj <= r。(i < j)
输出有多少对(i, j)。
思路:
二分法求,注意 i < j 这个范围。
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
typedef long long ll;
const int N = 2e5 + 5;
ll a[N];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int T;
cin >> T;
while(T--)
{
ll n, l, r;
int i;
cin >> n >> l >> r;
for(i = 0; i < n; ++i)
cin >> a[i];
sort(a, a+n);
ll ans = 0;
for(i = 0; i < n; ++i)
{
int templ = l - a[i];
int tempr = r - a[i];
ans += upper_bound(a+i+1, a+n, tempr) - lower_bound(a+i+1, a+n, templ);
}
cout << ans << endl;
}
return 0;
}