You are given a directed graph consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph acyclic by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.
Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n,u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
3 4 1 2 2 3 3 2 3 1
YES
5 6 1 2 2 3 3 2 3 1 2 1 4 5
NO
In the first example you can remove edge , and the graph becomes acyclic.
In the second example you have to remove at least two edges (for example, and ) in order to make the graph acyclic.
题意:给定一个有向图,问是否可以通过删一条边使得有向图无环。
思路:题目中边的数量十分庞大,因此不能直接搜删掉每条边的情况。可以先找任意一个环,若删除一条边可使整个图无环,则要删除的边一定位于该环上(该边为所有环的公共边),故对这个环上的每一条边进行删除后搜索有无环即可。
判断图是否有环可以用dfs,也可以用拓扑排序。
代码如下:
#include <bits/stdc++.h>
using namespace std;
int n,m;
int G[510][510],cir,vis[510],st,ed; //cir:有无环标记,st、ed:环的起点与终点
int p[510]; //记录结点的前驱
void dfs(int k)
{
vis[k]=1; //此节点已经被访问过一次
for (int i=1;i<=n;i++){
if (G[k][i]==1){
if (vis[i]==0){
p[i]=k;
dfs(i);
}
//找到任意一个环后,将环的一条边标记出来
else if (vis[i]==1){
cir=1;
st=k;
ed=i;
}
}
}
vis[k]=-1; //此节点所有的后继结点已被全部访问
}
int main()
{
while (~scanf("%d %d",&n,&m)){
memset(p,0,sizeof(p));
memset(G,0,sizeof(G));
memset(vis,0,sizeof(vis));
cir=0;
for (int i=0;i<m;i++){
int x,y;
scanf("%d %d",&x,&y);
G[x][y]=1;
}
//遍历整个图,寻找任意一个环
for (int i=1;i<=n;i++)
if (vis[i]==0)
dfs(i);
if (cir==0){
printf("yes\n");
continue;
}
//遍历找到的环上的每一条边,若删除之图中无环,则成立
int edgest=st,edgeed=ed;
while (edgest!=0&&cir==1){
G[edgest][edgeed]=0;
cir=0;
memset(vis,0,sizeof(vis));
for (int i=1;i<=n;i++)
if (vis[i]==0)
dfs(i);
G[edgest][edgeed]=1;
edgeed=edgest;
edgest=p[edgest];
}
if (cir==0)
printf("yes\n");
else
printf("no\n");
}
return 0;
}