랜덤 마라톤 · 코스 56

랜덤 마라톤 결과

A. 이름 궁합

실버 V 실버 V

길이 두배의 배열을 만들어서 인덱스 기준 짝수번째 위치(i « 1)에 a를, 홀수번째 위치(i « 1 | 1)에 b를 배치한 다음 문제에서 요구하는 대로 인접한 것들끼리 합해주면 됩니다.

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

int stroke[26] = {3, 2, 1, 2, 3, 3, 2, 3, 3, 2, 2, 1, 2,
                  2, 1, 2, 2, 2, 1, 2, 1, 1, 1, 2, 2, 1};

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

    string a, b;
    cin >> a >> b;

    vector<int> sum(a.size() + b.size());
    for (int i = 0; i < (int)a.size(); i++) {
        sum[i << 1] = stroke[a[i] - 'A'];
        sum[i << 1 | 1] = stroke[b[i] - 'A'];
    }

    for (int len = sum.size() - 1; len >= 2; len--) {
        for (int i = 0; i < len; i++) {
            sum[i] += sum[i + 1];
            sum[i] %= 10;
        }
    }

    print("{}{}", sum[0], sum[1]);
    return 0;
}

B. 배고파(Hard)

실버 III 실버 III

$m \le 10^{18} < 2^{60}$이므로 브루트 포스를 이용해 시간 복잡도 $O(60^2N)$에 해결할 수 있습니다.

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

using ll = long long;

ll m;
struct Answer {
    ll x, y, v;
    Answer(ll x, ll y) : x(x), y(y), v((1LL << x) + (1LL << y)) {}

    bool operator<(const Answer& a) const {
        if (abs(m - v) != abs(m - a.v))
            return abs(m - v) < abs(m - a.v);
        return v < a.v;
    }
};

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

    int n;
    cin >> n;

    for (int i = 0; i < n; i++) {
        cin >> m;

        Answer answer(60, 60);
        for (int x = 0; x <= 60; x++) {
            for (int y = x; y <= 60; y++) {
                answer = min(answer, Answer(x, y));
            }
        }

        print("{} {}\n", answer.x, answer.y);
    }

    return 0;
}

C. 트리 긋기

실버 II 실버 II

x좌표가 같은 점들끼리 세로로 연결하고, 나머지 점들은 각 x좌표마다 y좌표가 가장 작은 점들끼리만 이어주면 됩니다.

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

struct Point {
    int x, y, id;

    bool operator<(const Point& p) const {
        if (x != p.x)
            return x < p.x;
        return y < p.y;
    }
};

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

    int n;
    cin >> n;

    vector<Point> points(n);
    for (int i = 0; i < n; i++) {
        auto& [x, y, id] = points[i];
        id = i + 1;
        cin >> x >> y;
    }
    sort(points.begin(), points.end());

    Point& lowest = points.front();  // y좌표가 가장 작은 점
    for (int i = 1; i < n; i++) {
        if (lowest.x != points[i].x) {  // x좌표가 달라지면 y좌표가 가장 작은 점 업데이트
            print("{} {}\n", lowest.id, points[i].id);
            lowest = points[i];
            continue;
        }

        print("{} {}\n", points[i - 1].id, points[i].id);
    }

    return 0;
}

D. 2024는 무엇이 특별할까?

실버 I 실버 I

$K = 0$인 경우에 대해 생각해 봅시다. 약수 중 짝수인 것의 개수가 $0$이어야 하므로 소인수로 $2$를 갖지 않아야 함을 알 수 있습니다.

$K = 1$인 경우에 대해 생각해 봅시다. 홀수 $p$에 대해 $n = 2p$인 경우를 생각해 봅시다. 홀수인 약수의 개수는 $p$의 약수의 개수와 같습니다. 짝수인 약수는 홀수인 약수에 $2$를 곱한 것과 같으므로 $p$의 약수에 $2$을 곱한 것과 같습니다. 따라서 $\tau_e(n) = \tau_o(n)$입니다.

$K = 2$인 경우에 대해 생각해 봅시다. 홀수 $p$에 대해 $n = 2^2p$라면 홀수의 약수에 $2$를 곱한 것과 $2^2$를 곱한 것이 짝수인 약수가 되므로 $\tau_e(n) = 2\tau_o(n)$입니다.

일반화하여 $n = 2^Kp$라면 $\tau_e(n) = K\tau_o(n)$입니다. 따라서 $2^Kp \le N$을 만족하는 홀수 $p$의 개수가 정답입니다.

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

using ll = long long;

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

    if (k <= 62)
        print("{}\n", (n / (1LL << k) + 1) / 2);
    else
        print("0\n");
}

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

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

    return 0;
}

E. 짜고 치는 가위바위보 (Small)

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

constexpr int MOD = 1e9 + 7;

enum Hand { ROCK = 0, PAPER = 1, SCISSORS = 2 };

Hand getBeatingHand(Hand hand) {
    return Hand((hand + 1) % 3);
}

enum Winner { LIGHTER, SMALLANT, DRAW };

Winner getWinner(Hand lighter, Hand smallant) {
    if (getBeatingHand(lighter) == smallant)
        return SMALLANT;
    else if (getBeatingHand(smallant) == lighter)
        return LIGHTER;
    return DRAW;
}

map<char, Hand> handMap = {
    {'R', ROCK},
    {'P', PAPER},
    {'S', SCISSORS},
};

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

    char first;
    string s;
    cin >> first >> s;

    int n = s.size();

    int answer = 0;
    for (int choices = 1; choices < (1 << n); choices++) {
        bool resent = false;
        Hand beforeHand = handMap[first];
        Winner beforeWinner = DRAW;
        for (int i = 0; i < n; i++) {
            if (~choices & (1 << i))
                continue;

            Hand nowHand = handMap[s[i]];
            Winner nowWinner = getWinner(beforeHand, nowHand);

            if (nowWinner == DRAW and beforeWinner == LIGHTER) {
                resent = true;
                break;
            }

            swap(beforeHand, nowHand);
            swap(beforeWinner, nowWinner);
        }

        answer += not resent;
    }

    print("{}", answer % MOD);

    return 0;
}

F. 소수의 배수

골드 III 골드 III

포함 배제의 원리를 이용해 풀 수 있습니다.

각 소수의 배수를 한 번씩 모두 셉니다. 그렇다면 두 소수가 곱해진 것들은 두 번 세어지므로($ab = ba$) 두 소수의 곱의 배수를 배제합니다. 그렇다면 세 소수가 곱해진 것들은 두 번 배제되므로($(ab)c = c(ab)$) 다시 한 번씩 세어줍니다. 반복하여 홀수번 곱해진 경우는 세고, 짝수번 곱해진 경우는 배제합니다.

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;

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

    int n;
    ll m;
    cin >> n >> m;

    vector<ll> primes(n);
    for (int i = 0; i < n; i++)
        cin >> primes[i];

    ll answer = 0;
    for (int k = 1; k < (1 << n); k++) {
        ll product = 1;
        int count = 0;
        for (int i = 0; i < n; i++) {
            if (k & (1 << i)) {
                count++;
                product *= primes[i];
            }
        }

        if (count & 1)
            answer += m / product;
        else
            answer -= m / product;
    }

    print("{}", answer);

    return 0;
}

G. Astromeeting

골드 III 골드 III

모든 정점마다 한 번씩 비용의 합을 계산해 보면 됩니다. 저는 시간 초과를 우려하여 데이크스트라를 이용해 풀었는데, 플로이드-워셜로도 풀린다고 합니다.

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
80
81
82
83
84
85
86
87
88
89
90
#include <bits/stdc++.h>
#include <queue>
using namespace std;

template <typename T>
using minHeap = priority_queue<T, vector<T>, greater<T>>;
using ll = long long;

constexpr ll INF = 1LL << 40;

struct Answer {
    int num;
    ll totalCost;

    bool operator<(const Answer& a) const { return totalCost < a.totalCost; }
};

void solve() {
    int n, p, q;
    cin >> n >> p >> q;

    vector<int> meetings(n);
    for (int i = 0; i < n; i++) {
        cin >> meetings[i];
        meetings[i]--;
    }

    vector<vector<pair<ll, ll>>> adj(p, vector<pair<ll, ll>>());
    while (q--) {
        int i, j, d;
        cin >> i >> j >> d;
        i--, j--;
        adj[i].emplace_back(j, d);
        adj[j].emplace_back(i, d);
    }

    Answer answer(-1, INF);
    for (int i = 0; i < p; i++) {
        vector<ll> cost(p, INF);
        cost[i] = 0;
        vector<bool> reachable(p, false);
        reachable[i] = true;
        minHeap<pair<ll, int>> pq;
        pq.emplace(cost[i], i);

        while (not pq.empty()) {
            auto [nowCost, now] = pq.top();
            pq.pop();

            reachable[now] = true;

            if (nowCost > cost[now])
                continue;

            for (auto [next, edgeCost] : adj[now]) {
                ll nextCost = nowCost + edgeCost;
                if (nextCost < cost[next]) {
                    cost[next] = nextCost;
                    pq.emplace(nextCost, next);
                }
            }
        }

        bool allReachable = true;
        for (int v : meetings)
            allReachable &= reachable[v];
        if (not allReachable)
            continue;

        ll totalCost = 0;
        for (int v : meetings)
            totalCost += cost[v] * cost[v];

        answer = min(answer, Answer(i + 1, totalCost));
    }

    print("{} {}\n", answer.num, answer.totalCost);
}

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

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

    return 0;
}

G. 랜덤 넘버 추측하기

골드 I 골드 I

어느 시점에서 $i$번의 응모권을 개수를 $a_i$라 합시다. $k$번을 뽑으려면 랜덤 넘버 $X$는 아래를 만족해야 합니다.

\[\left(\sum^{k-1}_{i = 1}a_i\right) < X \le \left(\sum^{k}_{i = 1}a_i\right)\]

랜덤 넘버는 위 식을 만족하는 값을 아무거나 출력하면 되고, 그 때 $k$번의 응모권 개수 $a_k$를 $0$으로 만들어 주면 됩니다. 배열의 값이 변하는 구간 합은 세그먼트 트리를 이용해서 $O(\log N)$에 해결할 수 있습니다.

아래 코드에서는 $k - 1$이 인덱스를 벗어나는 것을 우려하여 $k$까지의 구간합을 출력했습니다.

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

struct SegmentTree {
    vector<int> t;
    int n;

    SegmentTree(const vector<int>& arr): n(arr.size()) {
        t = vector(n << 1, 0);

        for (int i = 0; i < n; i++)
            t[i+n] = arr[i];
        for (int i = n-1; i > 0; i--)
            t[i] = t[i << 1] + t[i << 1 | 1];
    }

    void set(int i, int v) {
        for (t[i+=n] = v; i > 1; i >>= 1)
            t[i >> 1] = t[i] + t[i ^ 1];
    }

    int getRangeSum(int l, int r) {
        int ret = 0;
        for (l+=n, r+=n; l <= r; l >>= 1, r >>= 1) {
            if (l & 1)
                ret += t[l++];
            if (~r & 1)
                ret += t[r--];
        }
        return ret;
    }

    struct Proxy {
        SegmentTree& tree;
        int i;

        Proxy& operator=(int v) {
            tree.set(i, v);
            return *this;
        }
    };

    Proxy operator[](int i) {
        return Proxy(*this, i);
    }
};

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

    int n, m;
    cin >> n >> m;
    vector<int> weights(n);
    for (int i = 0; i < n; i++)
        cin >> weights[i];

    SegmentTree tree(weights);
    for (int i = 0; i < m; i++) {
        int k;
        cin >> k;
        k--;

        cout << tree.getRangeSum(0, k) << ' ';
        tree[k] = 0;
    }

    return 0;
}

랜덤 마라톤 · 코스 56