Challenges Programming Contest --1.6.1 triangle

Title:
        n-stick, stick length i is ai. Want to choose the three sticks make up the perimeter of the triangle as long as possible. Please deliver maximum circumference, if it is unable to form a triangle output 0.

limitation factor

3 ≤ n ≤ 100

1 ≤ ai ≤ 10 ^ 6
input

n = 5

a = {2,3,4,5,10}

Export

12 (when selecting 3,4,5)

Entry

n = 4

a = {4,5,10,20}

Export

0 (no matter how the election can not form a triangle)

 

This question we all know O (the n- 3 ) method, but there is a way to O (nlog the n- ) to solve, and that is the sort.

Decreasing order, calculated from the beginning so that the maximum number of consecutive 3 to see if form a triangle, the triangle is the first solution to our solution can be constructed.

why?

Because if not three numbers in a row, that is, the presence of e + d> a then b + c must be greater than for a (since b + c> e + d), so if you find the largest contiguous three sides, so what we want answers .

 Code:

#include <bits/stdc++.h>
using namespace std;
int a[105];
bool flag;
bool cmp (int x, int y)
{
	return x > y;
}
int main(void)
{
	int n;
	scanf("%d", &n);
	for(int i = 0; i < n; i++)
	{
		scanf("%d", &a[i]); 
	}
	sort(a, a + n, cmp);
	for(int i = 0; i < n - 2; i++)
	{
	 	if(a[i] < a[i + 1] + a[i + 2])
	 	{
	 		flag = true;
	 		int ans = a[i] + a[i + 1] + a[i + 2];
	 		printf("%d\n", ans);
	 		break;
	 	}
	}
	if(!flag)
		printf("0\n");
	return 0;
}

  

Guess you like

Origin www.cnblogs.com/jacobfun/p/12173237.html