본문 바로가기

problem solving

1208번: 부분수열의 합2

상당히 어려웠던 문제다.

1182 부분수열의 합에서 확장된 버전인데 속도가 관건이다.

개수의 범위가 40까지이므로 한번의 재귀 호출로는 해결이 불가능해보인다.

나는 입력 받은 배열을 앞과 뒤, 둘로 나눠 계산을 진행했다.

(int형으로는 모든 케이스를 커버하지 못한다)

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <vector>
#include <algorithm>
 
 
int len, result;
std::vector<int> val;
std::vector<long long> frontSeq;
std::vector<long long> endSeq;
 
 
void DFS(int cur, long long sum, int limit) {
    if (cur == limit) {
        if (limit == len / 2) {
            frontSeq.push_back(sum);
        }
        else if (limit == len) {
            endSeq.push_back(sum);
        }
        return;
    }
 
    DFS(cur + 1, sum + val[cur], limit);
    DFS(cur + 1, sum, limit);
}
 
 
int main(void) {
    std::cin >> len >> result;
 
    int tmp;
    for (int i = 0; i < len; i++) {
        std::cin >> tmp;
        val.push_back(tmp);
    }
 
    DFS(00, len / 2);
    DFS(len / 20, len);
 
    std::sort(frontSeq.begin(), frontSeq.end());
    std::sort(endSeq.begin(), endSeq.end());
 
    long long count = 0;
    long long front = 0end = endSeq.size() - 1;
    while (front < frontSeq.size() && end >= 0) {
        if (frontSeq[front+ endSeq[end== result) {
            front++end--;
            long long fCnt = 1, eCnt = 1;
            while (front < frontSeq.size() && frontSeq[front== frontSeq[front - 1]) {
                front++;
                fCnt++;
            }
            while (end >= 0 && end < endSeq.size() && endSeq[end== endSeq[end + 1]) {
                end--;
                eCnt++;
            }
            count += fCnt * eCnt;
        }
        else if (frontSeq[front+ endSeq[end< result) {
            front++;
        }
        else if (frontSeq[front+ endSeq[end> result) {
            end--;
        }
    }
    
    if (result == 0) {
        count--;
    }
    std::cout << count << "\n";
    return 0;
}
cs

'problem solving' 카테고리의 다른 글

1759번: 암호 만들기  (0) 2020.02.22
1525번: 퍼즐  (0) 2020.02.22
1182번: 부분수열의 합  (0) 2020.02.20
1168번: 요세푸스 문제2  (0) 2020.02.19
1167번: 트리의 지름  (0) 2020.02.19