Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 그래프
- 재귀
- 다이나믹 프로그래밍
- 유니티
- c++
- 구현
- 정렬
- 유니온 파인드
- 알고리즘
- 그리디 알고리즘
- 우선순위 큐
- 누적 합
- 자료구조
- 투 포인터
- XR Interaction Toolkit
- 스택
- 시뮬레이션
- Unreal Engine 5
- BFS
- DFS
- VR
- Team Fortress 2
- ue5
- 수학
- 문자열
- 백준
- 브루트포스
- 다익스트라
- 백트래킹
- 트리
Archives
- Today
- Total
1일1알
백준 22857번 가장 긴 짝수 연속한 부분 수열(small) C++ 본문
포인터 두개 (start, end)를 이용해서 탐색을 하는데, start 인덱스의 원소가 짝수일 때만 검사하고, 홀수가 k+1 들어가있는 가장 작은 수열을 찾는다.
ex) 수열 S가 1, 2, 3, 4, 5, 6, 7, 8, 9 이고 K가 2라면 처음 찾는 수열은 2, 3, 4, 5, 6, 7 일 것이다. 이 수열에서 짝수로만 이루어져있는 수열은 2, 4, 6 이고 길이는 end - start - (cnt - 1)로 구할 수 있다. cnt는 찾은 홀수의 개수이고 1을 cnt에서 빼주는 이유는 홀수를 k개가 아닌 k+1개를 찾았기 때문에 더 찾은 1개를 cnt에서 빼주는 것이다.
그리고 찾은 수열을 일단 유지하면서 start를 이동시키고 start 인덱스의 원소가 홀수면 cnt를 줄여준다.
두번째 경우는 start 인덱스의 원소가 홀수이기 때문에 cnt만 1 줄여주고 다음으로 넘어갔다.
그리고 인덱스가 배열의 크기를 넘어가는 경우도 고려해야 한다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
using namespace std;
using ll = long long;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, k;
cin >> n >> k;
vector<int> v(n);
for (int i = 0; i < n; i++) {
cin >> v[i];
}
int ans = 0;
int start = 0;
int cnt = 0;
int end = start;
while (start < n) {
if (v[start] % 2 != 0) {
if (cnt > 0) cnt--;
start++;
continue;
}
if (start >= end) {
end = start;
cnt = 0;
}
while (cnt <= k) {
end++;
if (end >= n) break;
if (v[end] % 2 != 0) {
cnt++;
}
}
if (end >= n) end = n - 1;
ans = max(ans, end - start - cnt + 1);
start++;
}
cout << ans;
};
'알고리즘' 카테고리의 다른 글
백준 11722번 가장 긴 감소하는 부분 수열 C++ (0) | 2022.02.20 |
---|---|
백준 1633번 최고의 팀 만들기 C++ (0) | 2022.02.19 |
백준 1028번 다이아몬드 광산 C++ (0) | 2022.02.17 |
백준 1099번 알 수 없는 문장 C++ (0) | 2022.02.16 |
백준 2296번 건물짓기 C++ (0) | 2022.02.15 |