本题我观察到一个性质:路径上的点不能指向除了终点外出度为 0 的点。
然后我直接扔到里面做了
但显然他是错误的:
9 10
1 2
1 3
2 4
3 5
4 6
5 6
1 7
7 6
7 8
8 9
1 6
对于这一组数据,正确答案是 3,而我的程序输出为 2。
这是因为节点 8 并没有和终点 6 间接相连,我代码中仅判定了路径上的点不能连向 9。因此程序判定 1->7->6 是“合法的”。
但是还是在洛谷 A 了……所以请求加强数据!
代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 15, M = 2e5 + 15;
int h[N], e[M], ne[M], idx = 0;
void add(int a, int b) {
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
int n, m;
int s, t, d[N], dist[N];
bool flag[N];
bool st[N]; //1不能用
void dijkstra(int start) {
priority_queue< pair<int, int> > q;
memset(dist, 0x3f3f3f3f, sizeof dist);
q.push(make_pair(0, start)); dist[start] = 0;
while (q.size()) {
auto p = q.top(); q.pop();
int u = p.second;
if (st[u]) continue;
st[u] = 1;
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if (dist[v] > dist[u] + 1) {
dist[v] = dist[u] + 1;
q.push(make_pair(-dist[v], v));
}
}
}
}
int main() {
memset(h, -1, sizeof h);
scanf("%d%d", &n, &m);
while (m--) {
int u, v;
scanf("%d%d", &u, &v);
add(u, v); d[u]++;
}
scanf("%d%d", &s, &t);
for (int i = 1; i <= n; i++) {
for (int j = h[i]; ~j; j = ne[j]) {
int v = e[j];
if (d[v] == 0 && v != t) st[i] = 1;
}
}
for (int i = 1; i <= n; i++) cout << st[i] << ' '; puts("");
dijkstra(s);
printf("%d\n", dist[t]);
return 0;
}
(不要问我为什么写dijk,脑子抽了,好像bfs就行了……