728x90
반응형
https://www.acmicpc.net/problem/1940
1. Logic
정렬한 후 투포인터를 사용해서 m과 같은 갯수를 카운트해주면 된다.
2. Code
c++
#include<bits/stdc++.h>
using namespace std;
int n, m;
int ingredient[10000000];
int solve() {
int left = 0;
int right = n-1;
int cnt = 0;
while(left < right) {
if(ingredient[left]+ingredient[right] == m) cnt++;
if(ingredient[left]+ingredient[right] < m) left++;
else right--;
}
return cnt;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin >> n >> m;
for(int i = 0; i < n; i++) {
cin >> ingredient[i];
}
sort(ingredient, ingredient+n);
cout << solve();
}
Python
n =int(input())
m =int(input())
ingredient = list(map(int, input().split()))
ingredient.sort()
l = 0
r = n-1
cnt = 0
while l < r:
if ingredient[l] + ingredient[r] == m:
cnt += 1
if ingredient[l] + ingredient[r] >= m:
r -= 1
else:
l += 1
print(cnt)
알고리즘 Solve 후 제가 생각한 Logic을 기록하는 개인 공부 블로그입니다.
내용 중 최적화가 가능한 부분등은 언제든지 댓글로 틀린 부분 및 피드백 주시면 공부 및 반영하겠습니다🧐
728x90
반응형
'Algorithm > Beakjoon' 카테고리의 다른 글
[백준/Baekjoon] 14716 현수막 C++/Python :: BFS & DFS (1) | 2024.03.23 |
---|---|
[백준/Baekjoon] 2346 풍선 터뜨리기 C++/Python :: Date Structure (0) | 2024.03.14 |
[백준/Baekjoon] 1535 안녕 C++/Python :: Dynamic Programming (0) | 2024.03.07 |
[백준/Baekjoon] 11060 점프 점프 C++/Python :: BFS (0) | 2024.02.29 |
[백준/Baekjoon] 1270 전쟁-땅따먹기 C++/Python :: Implementation (1) | 2024.02.28 |