Author : Dipu Kumar Mohanto
CSE, Batch - 6
BRUR.
Problem Statement : 10944 - Nuts for nuts..
Source : Light Online Judge
Category : Dynamic Programing
Algorithm : Bitmask DP, TSP
Verdict : Accepted
- #include "bits/stdc++.h"
-
- using namespace std;
-
- #define pii pair <int, int>
-
- static const int maxn = 20 + 2;
-
- int row, column;
- char grid[maxn][maxn];
- pii ind[maxn];
-
- int getDis(int p, int q)
- {
- int r = abs(ind[p].first - ind[q].first);
- int c = abs(ind[p].second - ind[q].second);
- return max(r, c);
- }
-
- int getDis2(pii a, int p)
- {
- int r = abs(a.first - ind[p].first);
- int c = abs(a.second - ind[p].second);
- return max(r, c);
- }
-
- int dp[15][65540];
- bool memoize[15][65540];
- int n;
- pii L;
-
- int TSP(int now = 0, int mask = 0)
- {
- if (__builtin_popcount(mask) == n) return dp[now][mask] = getDis2(L, now);
- int &ret = dp[now][mask];
- bool &mem = memoize[now][mask];
- if (mem) return ret;
- mem = 1;
- int ans = INT_MAX;
- for (int nxt = 0; nxt < n; nxt++)
- {
- bool can = (bool)(mask & (1 << nxt));
- if (!can)
- {
- int go = getDis(now, nxt) + TSP(nxt, mask | (1 << nxt));
- ans = min(ans, go);
- }
- }
- return ret = ans;
- }
-
- int main()
- {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- #ifndef ONLINE_JUDGE
- freopen("in.txt", "r", stdin);
- #endif // ONLINE_JUDGE
- while (cin >> row >> column)
- {
- n = 0;
- for (int i = 1; i <= row; i++)
- {
- string s;
- cin >> s;
- for (int j = 1; j <= column; j++)
- {
- if (s[j-1] == 'L') L = pii(i, j);
- else if (s[j-1] == '#') ind[n++] = pii(i, j);
- }
- }
- if (n == 0)
- {
- cout << 0 << "\n";
- continue;
- }
- memset(memoize, 0, sizeof memoize);
- int ans = INT_MAX;
- for (int i = 0; i < n; i++)
- {
- int add = getDis2(L, i);
- int mask = 0;
- int tsp = TSP(i, mask | (1 << i)) + add;
- ans = min(ans, tsp);
- }
- cout << ans << "\n";
- }
- }
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.