반응형

https://www.acmicpc.net/problem/22862

 

22862번: 가장 긴 짝수 연속한 부분 수열 (large)

수열 $S$에서 최대 $K$번 원소를 삭제한 수열에서 짝수로 이루어져 있는 연속한 부분 수열 중 가장 긴 길이를 출력한다.

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. arr 배열에 수들을 입력받습니다.

 

2. s = 0, e = 0으로 설정한 후, arr[ 0 ]이 홀수이면 ans = 0, cnt = 1, 그렇지 않다면 ans = 1, cnt = 0으로 초기화합니다.

 

3. s <= e && e < N일 동안 반복해주면서 cnt <= K 일 때 e++ 그렇지 않다면 s++을 해주면서 ans = max(ans, e - s + 1 - cnt)를 통해 ans를 갱신해줍니다.

 

4. ans를 출력합니다.

 

[ 소스코드 ]

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include<iostream>
 
using namespace std;
 
int N, K;
int arr[1000000];
 
int main()
{
    scanf("%d %d"&N, &K);
 
    for (int i = 0; i < N; i++) {
        scanf("%d"&arr[i]);
    }
 
    int s, e;
    s = e = 0;
    int cnt = 0;
    int ans = 1;
 
    if (arr[0] % 2 == 1) {
        cnt = 1;
        ans = 0;
    }
 
    while (s <= e && e < N) {
 
        if (cnt <= K || s == e) {
            e++;
            if (arr[e] % 2 == 1) cnt++;
        }
        else {
            if (arr[s] % 2 == 1)cnt--;
            s++;
        }
 
        if (e < N) {
            ans = max(ans, e - s + 1 - cnt);
        }
    }
 
    printf("%d", ans);
}
cs
반응형

+ Recent posts