본문 바로가기

브루트 포스/브루트포스(재귀)

맞춰봐 (백트래킹)

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

 

1248번: Guess

Given a sequence of integers, a1, a2, …, an, we define its sign matrix S such that, for 1 ≤ i ≤ j ≤ n, Sij="+" if ai + … + aj > 0; Sij="−" if ai + … + aj < 0; and Sij="0" otherwise.  For example, if (a1, a2, a3, a4)=( −1, 5, −4, 2), then

www.acmicpc.net

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
#include <iostream>
#include <string>
using namespace std;
int n;
int sign[10][10];
int ans[10];
bool check(int index) {
    int sum = 0;
    for (int i = index; i >= 0; i--) {
        sum += ans[i];
        if (sign[i][index] == 0) {
            if (sum != 0return false;
        }
        else if (sign[i][index] < 0) {
            if (sum >= 0return false;
        }
        else if (sign[i][index] > 0) {
            if (sum <= 0return false;
        }
    }
    return true;
}
bool go(int index) {
    if (index == n) {
        return true;
    }
    if (sign[index][index] == 0) {
        ans[index] = 0;
        return check(index) && go(index + 1);
    }
    for (int i = 1; i <= 10; i++) {
        ans[index] = sign[index][index] * i;
        if (check(index) && go(index + 1)) return true;
    }
    return false;
}
int main() {
    cin >> n;
    string s;
    cin >> s;
    int cnt = 0;
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            if (s[cnt] == '0') {
                sign[i][j] = 0;
            }
            else if (s[cnt] == '+') {
                sign[i][j] = 1;
            }
            else {
                sign[i][j] = -1;
            }
            cnt += 1;
        }
    }
    go(0);
    for (int i = 0; i < n; i++) {
        cout << ans[i] << ' ';
    }
    cout << '\n';
    return 0;
}
cs

 

'브루트 포스 > 브루트포스(재귀)' 카테고리의 다른 글

부분수열의 합 (재귀, 비트마스크)  (0) 2023.03.21
로또  (0) 2023.03.20
부등호 (백트래킹)  (0) 2023.02.28
스타트와 링크  (0) 2023.02.28
퇴사  (0) 2023.02.27