Problem Description
You need walking from vertex S to vertex T in a graph. If you remove one vertex which stops you from walking from S to T, that vertex we call as key vertex. Now you are given a directed graph, S and T, and you should tell us how many key vertexes are there in the graph.
Please notice that S and T are key vertexes and if S cannot walking to T by the directed edge in the initial graph then all vertexes becomes to key vertexes.
Input
The input consists of multiply test cases. The first line of each test case contains two integers, n(0 <= n <= 100000), m(0 <= m <= 300000), which are the number of vertexes and the number of edge. Each of the next m lines consists of two integers, u, v(0 <= u, v < n; u != v), indicating there exists an edge from vertex u to vertex v. There might be multiple edges but no loops. The last line of each test case contains two integers, S, T(0 <= S, T < n, S != T).
Output
Output the number of key vertexes in a single line for each test case.
Sample Input
6 6
0 1
1 2
1 3
2 4
3 4
4 5
0 5
Sample Output
4
找起点和终点的割点,先用bfs算最短路,然后反复在最短路上dfs跳转到最远的点
#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define rep(i,j,k) for (int i = j; i <= k; i++)
const int N = 3e5 + 10;
int ft[N], nt[N], u[N], sz;
int n, m, x, y, dis[N], pre[N], flag[N], ans;
bool bfs()
{
queue<int> p; p.push(x);
while (!p.empty())
{
int q = p.front(); p.pop();
if (q == y)
{
for (int i = y; i != x; i = pre[i]) flag[i] = dis[i];
return true;
}
for (int i = ft[q]; i != -1; i = nt[i])
{
if (dis[u[i]]) continue;
pre[u[i]] = q; dis[u[i]] = dis[q] + 1;
p.push(u[i]);
}
}
return false;
}
int dfs(int x)
{
if (flag[x]) return x;
int res = x;
dis[x] = 1;
for (int i = ft[x]; i != -1; i = nt[i])
{
if (dis[u[i]]) continue;
int k = dfs(u[i]);
if (flag[res] < flag[k]) res = k;
}
return res;
}
int main()
{
while (scanf("%d%d", &n, &m) != EOF)
{
ans = sz = 0;
rep(i, 0, n) ft[i] = -1, dis[i] = flag[i] = 0;
while (m--)
{
scanf("%d%d", &x, &y);
u[sz] = y; nt[sz] = ft[x]; ft[x] = sz++;
}
scanf("%d%d", &x, &y);
if (!bfs()) { printf("%d\n", n); continue; }
rep(i, 0, n) dis[i] = 0;
for (int i = x, k; (k = dfs(i)) != y; flag[i = k] = 0) ans++;
printf("%d\n", ans + 2);
}
return 0;
}
标签:HDU,ft,int,Vertex,flag,key,return,3313,dis From: https://blog.51cto.com/u_15870896/5838732