题解 CF1149D Abandoning Roads

题意
一张 $n$ 个点 $m$ 条边的无向图,只有 $a,b$ 两种边权 $(a<b)$,对于每个 $i$,求图中所有的最小生成树中,从 $1$ 到 $i$ 距离的最小值。
题解
首先,根据最小生成树的求法,可以知道,一开始我们会先去选所有的 $a$ 边,然后再去再去选 $b$ 边,在没有 $b$ 边的时候,我们会得到一些连通块。原图最小生成树的形态一定是每个连通块内选一些边形成一个生成树,然后再将各个联通块通过 $b$ 边形成一棵新的生成树。

此时我们再去求 $1$ 到每个点的最短路。由于连通块构成了一棵大生成树,所以,不会有离开了一个连通块又回到该连通块的情况(因为这是一棵树,没有环,且树上最短路不会经过同一条边两遍),我们可以很自然的想到一个 DP,令 $dp[S][u]$ 表示当前已经离开的连通块编号的集合为 $S$,到 $u$ 的最短路为多少。这个可以用最短路算法求解,时间复杂度为 $\mathcal{O}(2^n(n+m)\log 2^n(n+m))$ 的算法,发现这个算法的时间复杂度还不足以通过本题,考虑思考一些性质。

对于一条从某个连通块出去又回来的路径,长度至少为 $2b$,而一个大小小于等于 $3$ 的连通块中,最远的两个点的距离也有 $2a$,所以这种情况会直接被最短路成立的条件给否决掉,可以不用记录在 $S$ 的状态中,于是,我们可以只用记录大小大于等于 $4$ 的连通块,这样的时间复杂度就为 $O(2^{\frac{n}{4}}(n+m)\log2^{\frac{n}{4}}(n+m))$,可以通过本题。

$\mathcal{View\ Code}$

#include <bits/stdc++.h>
using namespace std;
const int N = 75, M = 405, SIZE = (1 << 17) + 5;
int n, m, a, b, col[N], cnt, t, used[N], cc, vis[SIZE][N], dp[SIZE][N];
int tot, ver[M], nxt[M], edge[M], h[N];
void add(int x, int y, int z) {ver[++tot] = y, edge[tot] = z, nxt[tot] = h[x], h[x] = tot;}
struct node {int S, u, val;};
bool operator < (node a, node b) {return a.val > b.val;}
priority_queue <node> pq;
void dfs(int u) {
    used[u] = 1, cc++; 
    for(int i = h[u]; i; i = nxt[i])
        if(!used[ver[i]] && edge[i] == a) dfs(ver[i]);
}
void dfs2(int u, int c) {
    col[u] = c;
    for(int i = h[u]; i; i = nxt[i])
        if(col[ver[i]] == -1 && edge[i] == a) dfs2(ver[i], c);
}

int main() {
    memset(col, -1, sizeof(col));
    scanf("%d%d%d%d", &n, &m, &a, &b);
    for(int i = 1, x, y, z; i <= m; i++) {
        scanf("%d%d%d", &x, &y, &z), x--, y--;
        add(x, y, z), add(y, x, z);
    }
    for(int i = 0; i < n; i++)
        if(!used[i]) {
            cc = 0; dfs(i);
            if(cc >= 4) dfs2(i, cnt++);
        }
    t = cnt;
    memset(used, 0, sizeof(used));
    for(int i = 0; i < n; i++)
        if(!used[i]) {
            cc = 0; dfs(i);
            if(cc < 4) dfs2(i, cnt++);
        }
    memset(dp, 0x3f, sizeof(dp));
    pq.push({0, 0, 0});
    dp[0][0] = 0;
    while(pq.size()) {
        int u = pq.top().u, S = pq.top().S; pq.pop();
        if(vis[S][u]) continue; vis[S][u] = 1;
        for(int i = h[u]; i; i = nxt[i]) {
            int v = ver[i], w = edge[i];
            if(col[u] == col[v] && w == b) continue;
            if(col[v] < t && (S & (1 << col[v]))) continue;
            int cur = S;
            if(col[u] < t && col[v] != col[u]) cur |= (1 << col[u]);
            if(dp[cur][v] > dp[S][u] + w) {
                dp[cur][v] = dp[S][u] + w;
                if(!vis[cur][v]) pq.push({cur, v, dp[cur][v]});
            }
        } 
    }
    for(int i = 0; i < n; i++) {
        int res = 0x7fffffff;
        for(int j = 0; j < (1 << t); j++)
            res = min(res, dp[j][i]);
        printf("%d ", res);
    }
    return 0;
}

 

posted @ 2022-03-27 19:52  Dzhao_qwq  阅读(36)  评论(0)    收藏  举报