三角形性质
三条边中的任何两边之和都大于第三条边
栗子
输入n,p (个数,其中一条边长)
a[ i ] (n条边长,用于构成另外俩边)
样例分析:
共有9中可能
{16, 27}, {16, 35}, {16, 42}, {27, 35}, {27, 42}, {27, 51}, {35, 42}, {35, 51}, {42, 51}。
分析
主要分析极限条件,即两边之和等于第三边的情况
如果p不是最大,则满足条件的是小于a[i]+p的数
如果p是最大 , 则满足条件的是大于p-a[i]的数
重点:用lower_bound是为了多计入一位,这样避免x==y,x-y=0。
即要 upper_bound 和 lower_bound 一起使用
核心code:
i:1~n 读入 num[i]
long long sum = 0;
sort(num+1, num+n+1);
int x, y;
for(int i = 1; i <= n; i++)
{
x = lower_bound(num+i+1, num+n+1, p+num[i]) - (num+i+1); // 大于等于
y = upper_bound(num+i+1, num+n+1, abs(num[i]-p)) - (num+i+1); // 大于
sum += x-y;
}
cout << sum;