309. 코스튬 파티

아현·2021년 10월 6일
0

Algorithm

목록 보기
331/400
post-custom-banner

백준




1. 투포인터


최적화


import sys
input = sys.stdin.readline

n, m = map(int,input().split())
array = [int(input()) for _ in range(n)]
array.sort()
count = 0
right = n - 1
for left in range(n):
    if array[left] > m // 2:
        break
    while array[left] + array[right] > m:
        right -= 1
    
    count += right - left

print(count)





import sys
input = sys.stdin.readline

n, m = map(int,input().split())
array = [int(input()) for _ in range(n)]
array.sort()
count = 0

for left in range(n):
    right = left + 1
    while right < n:
        if array[left] + array[right] <= m:
            count += 1
        right += 1

print(count)




2. JavaScript


const solution = (n, s, array) => {
	let j = n - 1;
	let count = 0;

	array.sort((a, b) => a - b);
	for (let i = 0; i < n; i++) {
		if (array[i] > parseInt(s / 2)) break;
		while (array[i] + array[j] > s) j -= 1;
		count += j - i;
	}

	return count;
};

console.log(solution(4, 6, [3, 5, 2, 1]));


2. C++



#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
	int n, s;
	vector<int> data;
	cin >> n >> s;
	for (int i = 0, temp = 0; i < n; i++) {
		cin >> temp;
		data.push_back(temp);
	}

	sort(data.begin(), data.end());
	int j = n - 1;
	int count = 0;
	
	for (int i = 0; i < n; i++) {
		if (data[i] > int(s / 2)) break;
		while (data[i] + data[j] > s) j -= 1;

		count += j - i;
	}

	cout << count;
}

profile
For the sake of someone who studies computer science
post-custom-banner

0개의 댓글