一、题目要求
当三个国家中的任何两国实力之和都大于第三国的时候,这三个国家互相结盟就呈“三足鼎立”之势,这种状态是最稳定的。
现已知本国的实力值,又给出 n 个其他国家的实力值。我们需要从这 n 个国家中找 2 个结盟,以成三足鼎立。有多少种选择呢?
输入格式:
输入首先在第一行给出 2 个正整数 n(2≤n≤10e5)和 P(≤10e9),分别为其他国家的个数、以及本国的实力值。随后一行给出 n 个正整数,表示n 个其他国家的实力值。每个数值不超过 109,数字间以空格分隔。
输出格式:
在一行中输出本国结盟选择的个数。
输入样例:
7 30
42 16 2 51 92 27 35
输出样例:
9
样例解释:
能联合的另外 2 个国家的 9 种选择分别为:
{16, 27}, {16, 35}, {16, 42}, {27, 35}, {27, 42}, {27, 51}, {35, 42}, {35, 51}, {42, 51}。
二、思路
1、朴素版做法超时(n<=1e5,又用了两层for循环,会超时,似乎只能过两个测试点)
cin>>n>>p;
int i,j;
int cnt=0;
for(i=1;i<=n;i++)
cin>>a[i];
sort(a+1,a+1+n);
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
int x=a[i]+a[j];
int y=a[i]+p;
int z=a[j]+p;
if(x>p&&y>a[j]&&z>a[i])
{
cnt++;
}
}
}
cout<<cnt<<endl;
2.优化(二分)
upper_bound()找到第一个大于目标值的位置
lower_bound()找到第一个大于等于目标值的位置
upper_bound()底层实现采用二分查找的方式
三、代码
upper_bound(),lower_bound()
#include<bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
const int N=1e5+10;
/*
upper_bound()找到第一个大于目标值的位置
lower_bound()找到第一个大于等于目标值的位置
upper_bound()底层实现采用二分查找的方式
*/
int n,p;
int a[N];
void solve()
{
cin>>n>>p;
int i,j;
int cnt=0;
for(i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
// for(i=0;i<n;i++)
// cout<<a[i]<<' ';
// cout<<endl;
for(i=0;i<n;i++)
{
//从左到右查找第一个大于abs(p-a[i])的值
int l=upper_bound(a+i+1,a+n,abs(p-a[i]))-a;
//从左到右查找第一个大于等于p+a[i]的值
int r=lower_bound(a+i+1,a+n,p+a[i])-a;
//cout<<"l="<<l<<' '<<"r="<<r<<endl;
cnt+=(r-l);
}
cout<<cnt<<endl;
}
signed main()
{
int t=1;
while(t--)
{
//快输
/*
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
*/
solve();
}
return 0;
}
二分查找
#include<bits/stdc++.h>
#define endl '\n'
#define x first
#define y second
#define int long long
using namespace std;
typedef pair<int,int>PII;
const int N=2e5+10;
const int inf=0x3f3f3f3f;
int n,p;
int a[N];
void solve()
{
cin>>n>>p;
int i,j;
int cnt=0;
for(i=1;i<=n;i++)
cin>>a[i];
sort(a+1,a+1+n);
for(i=1;i<=n;i++)
{
int l=1,r=n;
while(l<r)
{
int mid=(l+r+1)/2;
//c<a+b; 取左边界
if(a[mid]<p+a[i])
l=mid;
else
r=mid-1;
}
int ll=1,rr=n;
while(ll<rr)
{
int mid=(ll+rr)/2;
int x=max(a[i]-p,p-a[i]);
if(a[mid]>x)
rr=mid;
else
ll=mid+1;
}
cnt+=l-ll+1;
if(i>=ll&&i<=l)
cnt--;
}
cout<<cnt/2<<endl;
}
signed main()
{
int t=1;
while(t--)
{
//快输
/*
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
*/
solve();
}
return 0;
}
/*
a+b>c;
a+c>b;
b+c>a;
c<a+b;
c>b-a;
c>a-b;
*/