问题描述:
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
大致题意:
给出一个有向图,给出起点(s),终点(t)。去掉一个点,则s不能到达t。这个点就称为割点。
问这个图中有多少个割点。
思路分析:
首先找出一个最短路。割点一定是在这条路上的。如果不是在这条路上,那么s就可以通过这条路到达t。
那么我们就把这个最短路上的点标记一下,再进行bfs,这次bfs不能走这个路径上的点。ans是这次bfs走到的最远的一个点。如果ans=t。那么割点就是s和t。如果不等t,那么ans就是一个割点,因为如果没有这个点就没法走下面的点。然后再以ans为起点,找能走到最远的一个点。一直重复这个过程。一直到ans=t。
ac代码:
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define maxn 100000+10
#define maxm 300000+100
#define inf 1000000000
struct Edge
{
int u,v,next;
}e[maxm];
int head[maxn],cnt;
int dis[maxn],mk[maxn];
int pre[maxn];
int in[maxn];
int n,m;
int s,t;
void add(int u,int v) //hash.
{
e[cnt].u=u;
e[cnt].v=v;
e[cnt].next=head[u];
head[u]=cnt++;
}
int solve()
{
int u,v,i;
memset(pre,-1,sizeof(pre));
memset(in,0,sizeof(in));
for(i=0;i<n;i++) dis[i]=-1;
dis[s]=0;
queue <int> Q;
Q.push(s);
while(!Q.empty()) //第一次bfs求最短路。
{
u=Q.front();Q.pop();
for(i=head[u];i!=-1;i=e[i].next)
{
v=e[i].v;
if(dis[v]==-1)
{
dis[v]=dis[u]+1; //距离?!
pre[v]=u; //记录前继节点。
Q.push(v);
}
}
}
if(dis[t]==-1) return n;
for(i=t;i!=s;i=pre[i]) in[i]=-1;
in[s]=-1;
int sum=1;
while(1)
{
int ans=-1,maxdis=-1;
Q.push(s);
while(!Q.empty())
{
u=Q.front();Q.pop();
for(i=head[u];i!=-1;i=e[i].next)
{
v=e[i].v;
if(in[v]==-1&&dis[v]>maxdis) //找出最远距离。
{
ans=v;
maxdis=dis[v];
}
else if(in[v]==0)
{
Q.push(v);
in[v]=1;
}
}
}
sum++;
if(ans==t) return sum;
s=ans;
}
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
int i,j;
int u,v;
for(i=0;i<n;i++) head[i]=-1;
cnt=0;
for(i=1;i<=m;i++)
{
scanf("%d%d",&u,&v);
add(u,v);
}
scanf("%d%d",&s,&t);
printf("%d\n",
());
}
return 0;
}