组合题5 个小题
已作答 0 / 5
给定一张有 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×105,1≤m≤4×105,1≤s,t≤n 且 s==t,1≤a,b≤n,可能出现重边。
以下程序通过 BFS 求出最小权值。请补全程序。
1#include <iostream>2constexpr int N = 200005;3constexpr int M = 400005;4int n, m, s, t;5int h[N], e[M << 1], ne[M << 1], w[M << 1], idx;6int q[N], d[N], c[N];7void add(int a, int b, int z) {8 e[idx] = b;9 w[idx] = z;10 ne[idx] = h[a];11 h[a] = idx++;12}13int main() {14 std::cin >> n >> m >> s >> t;15 for (int i = 1; i <= n; i++)16 h[i] = d[i] = c[i] = -1;17 for (int i = 0; i < m; i++) {18 int a, b;19 char op[2];20 std::cin >> a >> b >> op;21 int z = /* ① */;22 add(a, b, z);23 add(b, a, z);24 }25 int hh = 0, tt = 0;26 int p = 0, ng = 0, ok = 1;27 q[tt++] = s;28 d[s] = c[s] = 0;29 while (/* ② */) {30 int x = q[hh++];31 for (int i = h[x]; i != -1; i = ne[i]) {32 int y = e[i];33 if (w[i] > 0) p = 1;34 if (w[i] < 0) ng = 1;35 if (d[y] == -1) {36 d[y] = /* ③ */;37 c[y] = c[x] ^ 1;38 q[tt++] = y;39 } else if (/* ④ */)40 ok = 0;41 }42 }43 if (d[t] == -1) {44 std::cout << -1;45 return 0;46 }47 if (!p || !ng) {48 std::cout << d[t];49 return 0;50 }51 if (/* ⑤ */) std::cout << 0;52 else std::cout << 1;53 return 0;54}⑤处应填( )。