1. 程式人生 > 實用技巧 >Codeforces Round #688 (Div. 2)

Codeforces Round #688 (Div. 2)

A - Cancel the Trains

int main() {
    IOS;
    for (cin >> _; _; --_) {
        cin >> n >> m; VI a(n), b(m);
        for (auto &i : a) cin >> i;
        for (auto &i : b) cin >> i;
        int ans = 0;
        if (n > m) swap(n, m), swap(a, b);
        for (auto i : a) for (auto j : b) ans += i == j;
        cout << ans << '\n';
    }
    return 0;
}

B - Suffix Operations

就改一個數, 相當刪了一個數

int main() {
    IOS;
    for (cin >> _; _; --_) {
        cin >> n;
        rep (i, 1, n) cin >> a[i];
        ll ans = abs(a[n] - a[n - 1]), res = max(abs(a[2] - a[1]), ans);
        rep (i, 2, n - 1) {
            ll c = abs(a[i] - a[i - 1]); ans += c;
            umax(res, abs(a[i] - a[i - 1]) + abs(a[i + 1] - a[i]) - abs(a[i + 1] - a[i - 1]));
        }
        cout << ans - res << '\n';
    }
    return 0;
}

E - Dog Snacks

dfs 遍歷貪心就行哪個

int dfs(int x, int fa) {
    int mx = 0, mi = N;
    for (auto y : e[x]) {
        if (y == fa) continue;
        int dep = dfs(y, x);
        if (x - 1) umin(mi, dep), umax(mx, dep);
        else
            if (dep > mx) mi = mx, mx = dep;
            else umax(mi, dep);
    }
    if (x - 1 && e[x].size() > 2) return umax(k, mx + 1), mi + 1;
    else if (x - 1) return 1 + mx;
    if (e[x].size() == 1) return max(k, mx);
    return max(k, max(mx, mi + 1));
}
 
int main() {
    IOS;
    for (cin >> _; _; --_) {
        cin >> n; vector<VI>(n + 1).swap(e); k = 0;
        rep (i, 2, n) {
            int u, v; cin >> u >> v;
            e[u].pb(v); e[v].pb(u);
        }
        cout << dfs(1, -1) << '\n';
    }
    return 0;
}

F - Even Harder

f[i][k] 表示 唯一路徑到達i, 且上一個點 j 能最遠到達的點為 k, 則

目標為 f[n][n]

轉移方程為 f[i][a[j] + j] = min(f[i][a[j][j]], f[j][i - 1] + j~i-1能到i的點的數量)

int main() {
    IOS;
    for (cin >> _; _; --_) {
        cin >> n; rep (i, 1, n) cin >> a[i];
        rep (i, 2, n) {
            int c = 0;
            rep (j, i, n) f[i][j] = inf;
            per (j, i - 1, 1) if (j + a[j] >= i) umin(f[i][j + a[j]], f[j][i - 1] + c++);
            rep (j, i + 1, n) umin(f[i][j], f[i][j - 1]);
        }
        cout << f[n][n] << '\n';
    }
    return 0;
}