night.watchman's blog

By night.watchman, history, 18 months ago, In English

Problem

Can this problem be solved by creating a Graph and then applying DFS??

  • Vote: I like it
  • +5
  • Vote: I do not like it

»
18 months ago, # |
  Vote: I like it +5 Vote: I do not like it

Yes, of course. Build graph with edges i -> a[i] + i. But you also need to cache results of dfs.

#define int long long
map<int, int> mp;
int dfs(int v)
{
    if (v >= n) return 0;
    if (mp.find(v) != mp.end()) return mp[v];
    int res = 0;
    for (int u: g[v]) res = max(res, a[i] + dfs(u));
    return mp[v] = res;
}