Key Vertex
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 864 Accepted Submission(s): 218
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.
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
Author
momodi
Source
Recommend
wxl
给你一个无环有向图,让你求割点的数目。割点就是去掉以后无法从起点到达终点。
先用bfs找到一条最短路径,保存下来。然后再以s为起点找下一个割点,如果在第一次bfs时已经有了的点,就没有必要在加入队列了,那么在找的过程中离s最远的点就是下一个割点,不断的迭代,直到找到t为止。
#include<stdio.h>
#include<string.h>
#include<queue>
#define M 100000
using namespace std;
int head[M],vis[M],pre[M],low[M];
int ne;
int s,t,n,m;
struct Edg
{
int y,next;
}edg[M*3];
void addedge(int a,int b)
{
edg[ne].y=b;
edg[ne].next=head[a];
head[a]=ne++;
}
bool bfs1(int u)//第一次bfs找最短的路径
{
queue<int>q;
q.push(u);
vis[u]=1;
pre[u]=-1;
while(!q.empty())
{
int v=q.front();
q.pop();
for(int p=head[v];p!=-1;p=edg[p].next)
{
u=edg[p].y;
if(!vis[u])
{
q.push(u);
vis[u]=1;
pre[u]=v;
if(u==t)
return 1;
}
}
}
return 0;
}
int bfs2(int u)
{
queue<int>q;
q.push(u);
int res=u,w;
while(!q.empty())
{
u=q.front();
q.pop();
for(int p=head[u];p!=-1;p=edg[p].next)
{
w=edg[p].y;
if(!vis[w])
{
vis[w]=1;
if(low[w]==0)//如果在第一次中没有出现的话,就把这个点存下来
q.push(w);
else if(low[w]<low[res])//找离s最远的点
res=w;
}
}
}
return res;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(head,-1,sizeof(head));
memset(vis,0,sizeof(vis));
memset(low,0,sizeof(low));
ne=0;
for(int i=0;i<m;i++)
{
int a,b;
scanf("%d%d",&a,&b);
addedge(a,b);
}
scanf("%d%d",&s,&t);
if(n==0||n==1)
{
printf("%d\n",n);
continue;
}
if(s==t)
{
printf("1\n");
continue;
}
if(!bfs1(s))
{
printf("%d\n",n);
continue;
}
else//如果找到,就把它保存下来
{
int i=t;
int top=1;
while(pre[i]!=-1)
{
low[i]=top++;
i=pre[i];
}
low[s]=top;
}
memset(vis,0,sizeof(vis));
vis[s]=1;
int ans=1,v=s;
while(v!=t)//不断找割点
{
v=bfs2(v);
++ans;
}
printf("%d\n",ans);
}
return 0;
}