랜덤 마라톤 · 코스 55

랜덤 마라톤 결과

A. 새

브론즈 II 브론즈 II

$N$이 $0$이 될 때 까지 $k$씩 빼주면 됩니다. 뺀 횟수가 답이 됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    int answer = 0;
    for (int k = 1; n > 0; answer++, k++) {
        if (k > n)
            k = 1;
        n -= k;
    }

    cout << answer;
    return 0;
}

B. 3단 초콜릿 아이스크림

브론즈 I 브론즈 I

rev, tail 함수를 직접 만들어서 문제에서 요구하는 사항에 맞게 구현하면 됩니다.

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
#include <bits/stdc++.h>
using namespace std;

string rev(string s) {
    reverse(s.begin(), s.end());
    return s;
}

string tail(const string& s) {
    return s.substr(1);
}

void solve() {
    string s;
    cin >> s;

    string pref = s.substr(0, (s.size() + 3 - 1) / 3);
    cout << ((s == pref + rev(pref) + pref) or
             (s == pref + tail(rev(pref)) + pref) or
             (s == pref + rev(pref) + tail(pref)) or
             (s == pref + tail(rev(pref)) + tail(pref)))
         << '\n';
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int t;
    cin >> t;
    while (t--)
        solve();

    return 0;
}

C. 썸 팰린드롬

실버 II 실버 II

먼저 $9$만을 이용해서 합이 최대한 $N$에 가까워지게끔 합니다. 이때 필요한 $9$의 개수는 $\left\lfloor \dfrac{N}{18} \right\rfloor \times 2$으로 구할 수 있습니다. 그렇다면 나머지는 $N \bmod 18$이 되고, 이를 채우기 위한 최소 숫자의 개수를 구해주면 됩니다.

만약 한자리 수인 경우 숫자는 하나만 있어도 됩니다. 두 자리 수인 경우 적어도 두 개의 숫자가 필요한데, 홀수라면 숫자가 하나 더 필요합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    int answer = n / 18 * 2;
    n %= 18;
    if (n > 0) {
        if (n < 10)
            answer += 1;
        else
            answer += 2 + (n & 1);
    }

    cout << answer;

    return 0;
}

D. 완전 이진 트리

실버 I 실버 I

후위 순회를 통해 트리를 복구하면 됩니다.

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
#include <bits/stdc++.h>
using namespace std;

int k;
int visitedCnt = 0;

vector<int> visitOrder;
vector<vector<int>> nodesOfLevel;

void dfs(int level) {
    if (level <= k) {
        dfs(level + 1);
        nodesOfLevel[level].push_back(visitOrder[++visitedCnt]);
        dfs(level + 1);
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> k;

    visitOrder = vector<int>(1 << k);
    for (int i = 1; i < (int)visitOrder.size(); i++)
        cin >> visitOrder[i];

    nodesOfLevel = vector(k + 1, vector<int>());
    dfs(1);

    for (int i = 1; i <= k; i++) {
        for (int building : nodesOfLevel[i])
            cout << building << ' ';
        cout << '\n';
    }

    return 0;
}

E. 조건에 맞는 정수의 개수

실버 I 실버 I

길이가 $i$이고 마지막 숫자가 $j$로 끝나는 조건에 맞는 정수의 개수를 $dp[i][j]$로 둔 뒤 구해주면 됩니다.

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
#include <bits/stdc++.h>
using namespace std;

constexpr int MOD = 987'654'321;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    vector<vector<int>> dp(n + 1, vector(10, 0));
    for (int i = 1; i <= 9; i++)
        dp[1][i] = 1;

    for (int i = 2; i <= n; i++) {
        for (int j = 1; j <= 9; j++) {
            dp[i][j] += dp[i - 1][j];
            dp[i][j] %= MOD;

            if (j - 1 > 0) {
                dp[i][j] += dp[i - 1][j - 1];
                dp[i][j] %= MOD;
            }
            if (j - 2 > 0) {
                dp[i][j] += dp[i - 1][j - 2];
                dp[i][j] %= MOD;
            }

            if (j + 1 <= 9) {
                dp[i][j] += dp[i - 1][j + 1];
                dp[i][j] %= MOD;
            }
            if (j + 2 <= 9) {
                dp[i][j] += dp[i - 1][j + 2];
                dp[i][j] %= MOD;
            }
        }
    }

    int answer = 0;
    for (int i = 1; i <= 9; i++)
        answer = (answer + dp[n][i]) % MOD;
    cout << answer;

    return 0;
}

F. 알고리즘 수업 - 선택 정렬 4

골드 IV 골드 IV

먼저 우선순위 큐에 배열의 모든 원소를 넣습니다. 제일 큰 원소부터 하나씩 꺼내서 last와 교환하는 것을 반복하면 됩니다. 이때 각 원소들의 인덱스를 따로 저장해둬야 교환이 가능한데, 좌표 압축 후 인덱스로 관리하거나 맵을 사용하면 됩니다.

꼭 우선순위 큐를 사용할 필요는 없고, 매번 최댓값을 찾는 데 $O(\log N)$ 정도면 됩니다. 예를 들면 배열을 복사한 뒤 정렬해서 맨 뒤 부터 접근해도 됩니다.

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
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    map<int, int> index;
    priority_queue<int> maxHeap;

    int n, k;
    cin >> n >> k;

    vector<int> arr(n);
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
        index[arr[i]] = i;
        maxHeap.push(arr[i]);
    }

    for (int last = n - 1; k--; last--) {
        if (last == 0) {
            cout << -1;
            return 0;
        }

        int m = maxHeap.top(), lastElem = arr[last];
        maxHeap.pop();

        if (index[m] == last) {
            k++;
            continue;
        }

        swap(arr[index[m]], arr[last]);
        index[lastElem] = index[m];
        index[m] = last;
    }

    for (int i = 0; i < n; i++)
        cout << arr[i] << ' ';

    return 0;
}

G. MST 게임

골드 III 골드 III

크루스칼 알고리즘의 원리를 이용해 간선의 가중치가 가장 작은 것 부터 고려하면 됩니다. 스택의 top이 가장 가중치가 작도록 정렬한 다음 하나씩 꺼내보면서 최소 스패닝 트리를 만들면 됩니다.

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
73
74
75
76
77
78
79
#include <bits/stdc++.h>
using namespace std;

struct DisjointSet {
    vector<int> parent;

    DisjointSet(size_t size) : parent(size) {
        for (int i = 0; i < size; i++)
            parent[i] = i;
    }

    int findParent(int v) {
        if (parent[v] == v)
            return v;
        return parent[v] = findParent(parent[v]);
    }

    void unionParent(int u, int v) { parent[findParent(u)] = findParent(v); }
};

struct Edge {
    int from, to, weight;
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, m, k;
    cin >> n >> m >> k;

    stack<Edge> temp;
    for (int i = 1; i <= m; i++) {
        int from, to;
        cin >> from >> to;
        temp.emplace(from, to, i);
    }
    stack<Edge> edgeStack;
    while (not temp.empty())
        edgeStack.push(temp.top()), temp.pop();

    for (int turn = 0; turn < k; turn++) {
        int mstCost = 0;

        DisjointSet disjointSet(n + 1);
        stack<Edge> temp;

        for (int edgeCnt = 0; edgeCnt < n - 1;) {
            if (edgeStack.empty()) {
                mstCost = 0;
                break;
            }

            Edge edge = edgeStack.top();
            temp.push(edge);
            edgeStack.pop();

            if (disjointSet.findParent(edge.from) ==
                disjointSet.findParent(edge.to))
                continue;

            disjointSet.unionParent(edge.from, edge.to);
            mstCost += edge.weight;
            edgeCnt++;
        }

        while (not temp.empty()) {
            edgeStack.push(temp.top());
            temp.pop();
        }

        if (not edgeStack.empty())
            edgeStack.pop();

        cout << mstCost << ' ';
    }

    return 0;
}

H. 나눌 수 있는 부분 수열

골드 III 골드 III

수열의 $1$번째 항 부터 $i$번째 항까지의 합을 $S_i$라 합시다. $S_i \equiv 0 \pmod d$ 혹은 $j < i$에 대하여 $S_i \equiv S_j \pmod d$인 경우를 찾으면 됩니다. 후자의 경우 $j < i$인 $S_j \bmod d$의 개수를 세 주는 것으로 빠르게 구할 수 있습니다.

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
#include <bits/stdc++.h>
using namespace std;

using ll = long long;

void solve() {
    ll d, n;
    cin >> d >> n;

    vector<ll> arr(n);
    for (int i = 0; i < n; i++)
        cin >> arr[i];
    arr[0] %= d;
    for (int i = 1; i < n; i++)
        arr[i] = (arr[i] + arr[i - 1]) % d;

    vector<ll> remainderCnt(d);
    ll answer = 0;
    for (int i = 0; i < n; i++) {
        answer += remainderCnt[arr[i]]++;
        if (arr[i] == 0)
            answer++;
    }

    cout << answer << '\n';
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int c;
    cin >> c;
    while (c--)
        solve();

    return 0;
}

랜덤 마라톤 · 코스 55