[Codeforces 505C] Mr. Kitayuta, the Treasure Hunter

https://codeforces.ml/contest/505/problem/C

题意:
现有点\(0\)到点\(30000\),每个点都有一个权值。从点\(0\)开始跳,第一步跳\(d\)长。设上一步跳的长度为\(l\),那么下一步能在\([l - 1, l + 1]\)这个区间内选择一个值,以它为步长跳,但是要合法,即步长必须为正整数且不会跳出\(30000\)。

思路:
看着是很裸的\(dp\)或者记忆化搜索的做法,但\(n\)很大,直接\(O(n^2)\)跑过不去。观察一下步长,寻找一下不同的步长最多有多少个。从\(1\)开始,对公差为\(1\)的等差数列求和,发现在第\(245\)项时,和就会超过\(30000\)。但由于我们不知道具体会向哪边扩展,所以我们从\(d\)开始,向两边进行扩展,就能过滤掉永远取不到的步长,得到更优的决策集合,接下来大力推就行了。

#include <bits/stdc++.h>

using namespace std;

#define endl "\n"

inline int rd() {
    int f = 0; int x = 0; char ch = getchar();
    for (; !isdigit(ch); ch = getchar()) f |= (ch == '-');
    for (; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - '0';
    if (f) x = -x;
    return x;
}

typedef long long ll;

const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int N = 3e4 + 7;

int n, d;
int dp[N][1000], p[N], id[N];
vector<int> G;

void solve() {
    n = rd();
    d = rd();
    for (int i = 1; i <= n; ++i) {
        int q = rd();
        p[q]++;
    }
    int tot = 0;
    for (int i = max(1, d - 246); i <= min(30000, d + 246); ++i) {
        G.push_back(i);
        id[i] = tot++;
    }
    memset(dp, -0x3f, sizeof(dp));
    dp[d][ id[d] ] = p[d];
    int ans = p[d];
    for (int i = d; i <= 30000; ++i) {
        for (int j = 0; j < tot; ++j) {
            if (dp[i][j] < 0) continue;
            for (int k = -1; k <= 1; ++k) {
                int to = G[j] + k + i;
                if (to <= i || to > 30000) continue;
                dp[to][j + k] = max(dp[to][j + k], dp[i][j] + p[to]);
                ans = max(ans, dp[to][j + k]);
            }
        }
    }
    printf("%d\n", ans);
}

int main() {
    int t = 1;
    while (t--) solve();
    return 0;
}
上一篇:拓扑排序


下一篇:Codeforces Round #736 (Div. 2)C. Web of Lies(结论)