完善程序(第一题):平衡路线——BFS 求 |n+ − n−| 的最小值

kq547326 组合题 共 个子题

(1)(平衡路线)给定一张有 n 个顶点、m 条边的无向图,每条边带有符号 + 或 −。对于一条从顶点 s 到顶点 t 的路线,允许重复经过顶点和边,定义一条路线的权值如下:记 n+、n− 分别为经过的 + 边数和经过的 − 边数,则该路线的权值为 |n+ − n−|。 请计算从 s 到 t 的路线的最小权值。若不存在从 s 到 t 的路线,则输出 −1。 输入第一行为四个整数 n, m, s, t。接下来 m 行,每行给出两个整数 a, b 和一个字符 + 或 −,描述一条连接 a 与 b 的无向边及其符号。 数据满足 2 ≤ n ≤ 2 × 10^5,1 ≤ m ≤ 4 × 10^5,1 ≤ s, t ≤ n 且 s ≠ t,1 ≤ a, b ≤ 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;
}

子题 单选题

①处应填( )

A

op[0] == '+' ? 0 : 1

B

op[0] == '+'

C

op[0] == '+' ? 1 : -1

D

op[0] == '-' ? 1 : 0

子题 单选题

②处应填( )

A

hh < n

B

tt < n

C

hh <= tt

D

hh < tt

子题 单选题

③处应填( )

A

d[y] + 1

B

d[x] + 1

C

d[x]

D

d[x] - 1

子题 单选题

④处应填( )

A

c[y] == c[x]

B

w[i] == 1

C

c[y] != c[x]

D

d[y] + 1 != d[x]

子题 单选题

⑤处应填( )

A

ok && c[s] == c[t]

B

ok && c[s] != c[t]

C

!ok || c[s] == c[t]

D

!ok && c[s] != c[t]

正在加载题目数据…
已答 /
子题
该题型需在试卷/作业中作答,单题练习暂不支持
答案解析
讨论
发布
登录后参与讨论 立即登录
发布讨论需先绑定并验证手机号 去绑定手机号
加载中…
我
我
回复 @
回复 @
发送
还没有人讨论,来发表第一条吧