三角形最长周长nlogn解法

本文介绍了一种从给定的n根棍子中找出能构成周长最长三角形的三根棍子的有效算法。通过排序和逆序遍历,确保所选三根棍子能构成三角形的同时实现O(nlogn)的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看了看白书,一个题目:

给n根棍子,长度分别为a[i],选出3个组成周长尽可能长的三角形。

书下面专门写了个有nlogn的解法,我还想不出来。。。惭愧。

解决方法其实很简单,排个序,然后只需要挨个判断左边两个相邻的边能否组成三角形即可。因为如果相邻的无法组成三角形,更左边的就更不可能了。感觉自己好傻逼。。

还是贴个代码吧

#include<set>
#include<map>
#include<cmath>
#include<ctime>
#include<queue>
#include<cstdio>
#include<string>
#include<vector>
#include<cstdlib>
#include<cstring>
#include<iomanip>
#include<iostream>
#include<algorithm>
#define fi first
#define se second
#define pb push_back
#define lowbit(x) x&(-x)
#define PII  pair<int, int> 
#define FAST ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int mod = (int)1e9 + 7;
const int maxn = (int)1e5 + 5;
using namespace std;

int a[maxn];

int main()
{
	int n; scanf("%d", &n);
	for(int i = 1; i <= n; i++) scanf("%d", a + i);
	sort(a + 1, a + 1 + n);
	bool flag = false;
	for(int i = n; i >= 3; i--){
		if(a[i] < a[i-1] + a[i-2]){
			printf("%d %d %d\n", a[i-2], a[i-1], a[i]);
			flag = true;
			break;
		}
	}
	if(!flag) puts("-1");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值