LightOJ 1057 Collecting Gold(状压DP)

topic

nm,(n,m)<(20,20) There is a person on the grid chart of, and no more than 15 gold mines; ask this person to get all the gold mines from the current location and then return to this location the minimum distance? You can only go in four adjacent directions at a time;

Ideas

Because there are no obstacles, it is very convenient to calculate the distance between the two grids; at the
beginning, all the order of obtaining gold ore is exhausted, and then TLE; at the
end, the state is over, dp[sta][i] means reaching The minimum distance of state sta on the i-th gold mine;

char mp[22][22];
int dp[(1 << 16) + 1][16];
int dis(ii a, ii b) {
    return max(abs(a.first - b.first) , abs(a.second - b.second));
}
int main(int argc, const char * argv[])
{
    int kase;cin >> kase;
    while(kase--) {
        int n, m;scanf("%d%d", &n, &m);
        Rep(i, 1, n) scanf("%s", mp[i] + 1);
        ii st;
        vector<ii> v;
        Rep(i, 1, n) {
            Rep(j, 1, m) {
                if (mp[i][j] == 'x') st = ii(i, j);
                if (mp[i][j] == 'g') v.push_back(ii(i, j));
            }
        }
        memset(dp, inf, sizeof dp);
        int Size = (int)v.size();
        for (int i = 0;i < Size;++i)
            dp[1 << i][i] = dis(st, v[i]);
        for (int sta = 1;sta < 1 << Size;++sta) {
            for (int i = 0;i < Size;++i) {
                if ((sta & (1 << i)) && dp[sta][i] != inf) {
                    for (int j = 0;j < Size;++j) {
                        if ((sta & (1 << j)) == 0) {
                            //i -> j
                            dp[sta | (1 << j)][j] = min(dp[sta | (1 << j)][j], dp[sta][i] + dis(v[i], v[j]));
                        }
                    }
                }
            }
        }
        int ans = inf;
        for (int i = 0;i < Size;++i)
            ans = min(ans, dp[(1 << Size) - 1][i] + dis(v[i], st));
        if (Size == 0) ans = 0;
        printf("Case %d: %d\n", ++nCase, ans);
    }

    // showtime;
    return 0;
}

Guess you like

Origin blog.csdn.net/KIJamesQi/article/details/55099976