光玉小镇

光玉小镇

https://ac.nowcoder.com/acm/contest/6874/C

题意

给定一个字符串的图,让你处理一个图的问题。给定不超过15个点的图,让你求从起点遍历完所有点并回到起点的最小花费。

题解

我们可以把s和t抽出来建图,然后跑最短路建立点之间的关系。然后我们用状压dp求解遍历完所有点的花费,最后加上(点数-1)*t,即为整个的花费。

代码

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 17;
const int MAXM = 2e2 + 7;
const int INF = 0x3f3f3f3f;
char s[MAXM][MAXM];
int dp[MAXN][1 << MAXN], n, m, t;
int dis[MAXM][MAXM];
int g[MAXM][MAXM];
vector<pair<int, int> > p;
const int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
void bfs(int sx, int sy) {
    queue<pair<int, int> > q;
    q.push(make_pair(sx, sy));
    memset(dis, 0x3f, sizeof(dis));
    dis[sx][sy] = 0;
    while (!q.empty()) {
        pair<int, int> u = q.front(); q.pop();
        for (int i = 0; i < 4; i++) {
            int dx = dir[i][0] + u.first;
            int dy = dir[i][1] + u.second;
            if (dx < 0 || dx >= n || dy < 0 || dy >= m || s[dx][dy] == '#') continue;
            if (dis[dx][dy] > dis[u.first][u.second] + 1) {
                dis[dx][dy] = dis[u.first][u.second] + 1;
                q.push(make_pair(dx, dy));
            }
        }
    }
}
void solve() {
    scanf("%d%d%d", &n, &m, &t);
    for (int i = 0; i < n; i++) scanf("%s", s[i]);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (s[i][j] == 'S' || s[i][j] == 'T') {
                p.push_back(make_pair(i, j));
            }
        }
    }
    for (int i = 0; i < p.size(); i++) {
        if (s[p[i].first][p[i].second] == 'S') {
            swap(p[i], p[0]);
            break;
        }
    }
    for (int i = 0; i < p.size(); i++) {
        bfs(p[i].first, p[i].second);
        for (int j = 0; j < p.size(); j++) {
            g[i][j] = dis[p[j].first][p[j].second];
        }
    }
    memset(dp, 0x3f, sizeof(dp));
    dp[0][1] = 0;
    n = p.size();
    for (int i = 0; i < (1 << n); i++) {
        for (int j = 0; j < n; j++) {
            if (i >> j & 1) {
                for (int k = 0; k < n; k++) {
                    dp[j][i] = min(dp[j][i], dp[k][i ^ (1 << j)] + g[k][j]);
                }
            }
        }
    }
    int ret = 0x3f3f3f3f;
    for (int i = 0; i < n; i++) {
        ret = min(ret, dp[i][(1 << n) - 1] + g[i][0]);
    }
    if (ret == INF) {
        printf("-1\n");
        return;
    }
    printf("%lld\n", (long long)(n - 1) * (long long)t + (long long)ret);
}
int main() {
    solve();
    return 0;
}
全部评论

相关推荐

点赞 评论 收藏
分享
评论
2
收藏
分享
牛客网
牛客企业服务