Chavanbhai1's blog

By Chavanbhai1, history, 3 days ago, In English

question link : https://www.spoj.com/problems/HIST2/

include <bits/stdc++.h>

using namespace std;

define fastio() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)

int n; vector a; vector<vector<pair<int, int>>> dp;

pair<int, int> rec(int mask, int last) { int index = __builtin_popcount(mask);

if (index == n - 1) {
    for (int i = 0; i < n; ++i) {
        if (!((mask >> i) & 1))
            return {2 + abs(a[last] - a[i]) + a[i], 1};
    }
}

if (dp[mask][last] != make_pair(-1, -1))
    return dp[mask][last];

pair<int, int> ans = {-1e9, 0};
for (int i = 0; i < n; ++i) {
    if (!((mask >> i) & 1)) {
        int tempAns = 2 + abs(a[last] - a[i]);
        auto p = rec(mask | (1 << i), i);

        p.first += tempAns;
        if (ans.first < p.first) {
            ans = p;
        } else if (ans.first == p.first) {
            ans.second += p.second;
        }
    }
}

return dp[mask][last] = ans;

}

void solve() { dp.assign((1 << (n+1)), vector<pair<int, int>>(n + 1, {-1, -1})); auto ans = rec(0, n); cout << ans.first << " " << ans.second << "\n"; }

int32_t main() { fastio(); while (true) { cin >> n; if (n == 0) break;

a.resize(n + 1, 0);
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
    }

    solve();
}
return 0;

} What can be the issue i am not able to find any flaw in this ?

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
3 days ago, # |
  Vote: I like it 0 Vote: I do not like it

I was also solving same question few days back and stuck at same point :(