[Codility] Triangle

hamsteak·2023년 10월 10일
0

ps

목록 보기
27/39

배열 A가 주어졌을 때 다음 조건을 만족하는 경우가 있는지 찾는 문제.

0<=P<Q<R<A0<=P<Q<R<A_sizesize
A[P]+A[Q]>A[R]A[P] + A[Q] > A[R],
A[Q]+A[R]>A[P]A[Q] + A[R] > A[P],
A[R]+A[P]>A[Q]A[R] + A[P] > A[Q]

비슷한 크기의 값들만 비교하더라도 만족 여부를 판단할 수 있다. 두 원소의 합이 int의 범위를 벗어날 수 있으므로 주의해야한다.

https://app.codility.com/programmers/lessons/6-sorting/triangle/

cpp code

#include <algorithm>
using lld = long long int;
int solution(vector<int> &A) {
    sort(A.begin(), A.end(), less<int>());
    for (int i=0; i+2<A.size(); i++) {
        bool succeed = true;
        for (int j=0; j<3; j++) {
            lld t[3];
            for (int k=0; k<3; k++) {
                t[k] = A[i + (j + k) % 3];
            }
            if (t[0] + t[1] <= t[2]) succeed = false;
        }
        if (succeed) return true;
    }
    return false;
}
profile
안녕하세요

0개의 댓글