Triangle(给了一系列数,判断能不能选出三个数构成三角形)

Problem Description

After Xiaoteng took a math class, he learned a lot of different shapes, but Xiaoteng's favorite triangle is because he likes stable shapes, just like his style. 

After the Xiaoxun knew it, he wanted to give a triangle as a gift to Xiaoteng. He originally planned to do one, but he was too tired. So he decided to bring some wooden sticks to Xiaoteng and let Xiaoteng make a triangle himself. 

One day, Xiaoxun brought n sticks to Xiaoteng. Xiaoteng wanted to try to use three of them to form a triangle, but the number is too much, Xiaoteng stunned, so he can only ask for your help.

 

 

Input

There are mutiple test cases.

Each case starts with a line containing a integer  n(1≤n≤5×106)  which represent the number of sticks and this is followed by n positive intergers(smaller than 231−1) separated by spaces.

Output

YES or NO for each case mean Xiaoteng can or can't use three of sticks to form a triangle.

 

Sample Input

4

1 2 3 4

Sample Output

YES

Source

2019中山大学程序设计竞赛(重现赛)

题意:输入n代表有n个数,问能不能从中选出三个构成三角形。

思路:我的思路就是:排序相邻两个数的差值很肯定最小,然后二分去找(最接近这两个数之和的那个数),比较差值和这个数的大小。

           大佬的知识:如果没有三角形,那么数列是斐波拉契数列级别增长,所以个数<50;

我的思路AC代码:

#include<bits/stdc++.h>
#define N 5000010
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;
int a[N];
void read(int &x)
{
    char s=getchar();
    while(~s&&s<'0'||s>'9')s=getchar();
    x=s-'0';
    while(~(s=getchar())&&s>='0'&&s<='9')x=x*10+s-'0';
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        for(int i=0; i<n; i++)
            scanf("%d",&a[i]);
        int flag=0;
        for(int i=1;i<n;i++)
        {
            ll x=a[i]+a[i-1];
            ll y=a[i]-a[i-1];
            int z=lower_bound(a+i+1,a+n,x)-a-1;
            if(z>i&&y<a[z])
            {
                flag=1;
                break;
            }
        }
        if(flag)printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}

运用大佬的知识AC代码:

#include<bits/stdc++.h>
using namespace std;
#define N 5000010
int a[N];
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        for(int i=0; i<n; i++)
            scanf("%d",&a[i]);
        int flag=0;
        if(n>100)flag=1;
        else if(n>=3)
        {
            for(int i=2; i<n; i++)
                if(a[i]<a[i-1]+a[i-2])
                {
                    flag=1;
                    break;
                }
        }
        if(flag)printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值