题意:n个点,m条边的有向图,给出目标点,求与该点直接相连的点,且这些点不存在第二条路径与目标点相通。
题解:bfs
先将目标点从图中拿走,再反向建图。
用集合s表示能直接到达目标点的点集,我们从这些点开始bfs,若存在两条路径到达点集s中的某个点x,那么x就不符合条件。若继续bfs,复杂度会是n2 ,其实若该点属于点集s,且已经访达两次,那么之后的点不需要再访问了,因为肯定也访达了两次。
因为要判环,我们直接用一个vector表示vis,同时存储是从哪个点开始bfs的。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
const int maxn = 1e5 + 5;
int n, m, a, x, y;
vector<int> v[maxn], s, ans, fa[maxn];
void bfs() {
queue<pair<int, int> > q;
for (auto i : s) {
q.push(make_pair(i, i));
fa[i].push_back(i);
}
while (!q.empty()) {
pair<int, int> temp = q.front();
x = temp.first;
q.pop();
for (auto i : v[x]) {
if (i == temp.second) continue;
if (fa[i].size() == 0) {
q.push(make_pair(i, temp.second));
fa[i].push_back(temp.second);
}
else if (fa[i].size() == 1) {
if (fa[i][0] != temp.second) fa[i].push_back(temp.second);
q.push(make_pair(i, temp.second));
}
}
}
}
int main() {
scanf("%d%d%d", &n, &m, &a);
for (int i = 1; i <= m; i++) {
scanf("%d%d", &x, &y);
if (y == a) {
s.push_back(x);
continue;
}
v[y].push_back(x);
}
bfs();
for (auto i : s) {
if (fa[i].size() == 1) ans.push_back(i);
}
sort(ans.begin(), ans.end());
printf("%d\n", ans.size());
for (auto i : ans) printf("%d\n", i);
return 0;
}