题解:AT_abc244_f [ABC244F] Shortest Good Path

· · 题解

题目传送门

题意简化

给定一个无向连通图,存在 2^n 种 01 串 S,每种串规定每个顶点在路径中出现次数为奇 / 偶数。输出所有合法串的最短路径长度之和。

solution

看到数据范围:N \le 17,容易想到状压。

  1. 状态 (tt, u):tt 为奇偶状态,u 是路径的终点,dis_{tt,u} 存到达该状态的最短路径长度;
  2. 转移:u 的邻点 v,新的奇偶状态为 tt \oplus (1 << v),长度 +1,未访问则更新入队;
  3. 遍历全部状态累加 res 得到答案。

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 3e5 + 5, INF = 1e18;
struct node {
    int tt, u;
};
queue<node> q;
int n, m, dis[N][25], res[N];
vector<int> g[N];
void bfs() {
    for (int i = 0; i < n; i++) {
        if (!dis[1 << i][i]) {
            dis[1 << i][i] = 1;
            q.push({1 << i, i});
            res[1 << i] = min(res[1 << i], 1ll);
        }
    }
    while (!q.empty()) {
        node hh = q.front();
        q.pop();
        int u = hh.u, tt = hh.tt;
        for (int v : g[u]) {
            int tmp = tt ^ (1 << v);
            if (!dis[tmp][v]) {
                dis[tmp][v] = dis[tt][u] + 1;
                q.push({tmp, v});
                res[tmp] = min(res[tmp], dis[tt][u] + 1);
            }
        }
    }
}
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    cin >> n >> m;
    int maxx = (1 << n) - 1;
    fill(res + 1, res + maxx + 1, INF);
    res[0] = 0;
    for (int i = 1, u, v; i <= m; i++) {
        cin >> u >> v;
        g[u - 1].push_back(v - 1);
        g[v - 1].push_back(u - 1);
    }
    bfs();
    int ans = 0;
    for (int i = 0; i <= maxx; i++) {
        if (res[i] != INF) {
            ans += res[i];
        }
    }
    cout << ans;
    return 0;
}