題目

D - Line++

BFS 可以 $O(N)$ 內找到單源最短路徑(edge weight = 1),所以就對每一個點 BFS 一下即可。

AC Code

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

typedef long long ll;
typedef pair<int, int> ii;

int main()
{
    int n, x, y;
    scanf("%d %d %d", &n, &x, &y);
    x--, y--;

    vector<int> g[n];
    for (int i = 0; i < n - 1; i++) {
        g[i + 1].push_back(i);
        g[i].push_back(i + 1);
    }
    g[x].push_back(y);
    g[y].push_back(x);

    int ans[n] = {0};
    for (int i = 0; i < n; i++) {
        // bfs
        queue<int> q;
        q.push(i);
        bool used[n] = {false};
        int dist[n] = {0};
        used[i] = true;
        dist[i] = 0;
        while (q.size() > 0) {
            int cur = q.front();
            q.pop();

            for (auto v : g[cur]) {
                if (used[v])
                    continue;
                q.push(v);
                used[v] = true;
                dist[v] = dist[cur] + 1;
            }
        }

        for (int j = 0; j < n; j++) {
            ans[dist[j]]++;
        }
    }

    for (int i = 1; i <= n - 1; i++)
        printf("%d\n", ans[i] / 2);

    return 0;
}

E - Red and Green Apples

這題其實就是把 紅色 跟 綠色 的前 x 跟 y 大的數值拿出來。之後,這 $x+y$ 個數字中,從小的開始去跟 clear 的最大數換。

下面這是如果你跟我一樣 QQ 用錯 greedy 策略的話會 WA 的 test case

1
2
3
4
2 3 2 3 3
10 8
6 4 2
9 7 5

AC Code

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

typedef long long ll;
typedef pair<int, int> ii;

void mySort(vector<int> &inp)
{
    sort(inp.begin(), inp.end());
    reverse(inp.begin(), inp.end());
}

int main()
{
    int x, y, a, b, c;
    scanf("%d %d %d %d %d", &x, &y, &a, &b, &c);

    vector<int> red, green, cand;
    for (int i = 0; i < a; i++) {
        int num;
        scanf("%d", &num);
        red.push_back(num);
    }
    for (int i = 0; i < b; i++) {
        int num;
        scanf("%d", &num);
        green.push_back(num);
    }
    for (int i = 0; i < c; i++) {
        int num;
        scanf("%d", &num);
        cand.push_back(num);
    }

    mySort(red);
    mySort(green);
    mySort(cand);

    vector<int> orig;
    for (int i = 0; i < x; i++)
        orig.push_back(red[i]);
    for (int i = 0; i < y; i++)
        orig.push_back(green[i]);
    mySort(orig);

    int j = 0;
    for (int i = x + y - 1; i >= 0 && j < c; i--) {
        if (cand[j] > orig[i]) {
            orig[i] = cand[j];
            j++;
        }
    }

    ll ans = 0;
    for (int i = 0; i < x + y; i++)
        ans += orig[i];
    printf("%lld\n", ans);

    return 0;
}