← 查看本卷题目
组合题5 个小题
已作答 0 / 5

给定一张有 nn 个顶点、mm 条边的无向图,每条边带有符号 '+' 或 '-'。对于一条从顶点 ss 到顶点 tt 的路线,允许重复经过顶点和边。定义一条路线的权值如下:记 n+,n−n^{+}, n^{-} 分别为经过的 '+' 边数和经过的 '-' 边数,则该路线的权值为 ∣n+−n−∣∣n^{+}- n^{-}∣。

请计算从 ss 到 tt 的路线的最小权值。若不存在从 ss 到 tt 的路线,则输出 −1。

输入第一行为四个整数 n,m,s,tn, m, s, t。接下来 mm 行,每行给出两个整数 a,ba, b 和一个字符 '+' 或 '-',描述一条连接 aa 与 bb 的无向边及其符号。

数据满足 2≤n≤2×1052 \le n \le 2 \times 10^{5},1≤m≤4×1051 \le m \le 4 \times 10^{5},1≤s,t≤n1 \le s, t \le n 且 s≠=ts ≠=t,1≤a,b≤n1 \le a, b \le n,可能出现重边。

以下程序通过 BFS 求出最小权值。请补全程序。

#include <iostream>constexpr int N = 200005;constexpr int M = 400005;int n, m, s, t;int h[N], e[M << 1], ne[M << 1], w[M << 1], idx;int q[N], d[N], c[N];void add(int a, int b, int z) {    e[idx] = b;    w[idx] = z;    ne[idx] = h[a];    h[a] = idx++;}int main() {    std::cin >> n >> m >> s >> t;    for (int i = 1; i <= n; i++)        h[i] = d[i] = c[i] = -1;    for (int i = 0; i < m; i++) {        int a, b;        char op[2];        std::cin >> a >> b >> op;        int z = /* ① */;        add(a, b, z);        add(b, a, z);    }    int hh = 0, tt = 0;    int p = 0, ng = 0, ok = 1;    q[tt++] = s;    d[s] = c[s] = 0;    while (/* ② */) {        int x = q[hh++];        for (int i = h[x]; i != -1; i = ne[i]) {            int y = e[i];            if (w[i] > 0) p = 1;            if (w[i] < 0) ng = 1;            if (d[y] == -1) {                d[y] = /* ③ */;                c[y] = c[x] ^ 1;                q[tt++] = y;            } else if (/* ④ */)                ok = 0;        }    }    if (d[t] == -1) {        std::cout << -1;        return 0;    }    if (!p || !ng) {        std::cout << d[t];        return 0;    }    if (/* ⑤ */) std::cout << 0;    else std::cout << 1;    return 0;}
第 35 题单选题原卷 3 分

②处应填( )。

填写答案