D. Almost Acyclic Graph
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
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).
Input
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).
Output
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
Examples
input
Copy
3 4
1 2
2 3
3 2
3 1
output
Copy
YES
input
Copy
5 6
1 2
2 3
3 2
3 1
2 1
4 5
output
Copy
NO
Note
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.
题意:给你一个n个点,m条边的一个有向图,问在最多删除一条边的情况是否还有环存在,有的话输出NO,没有的话输出YES。
思路:分两种情况,一种是不删除边的情况,一种是删除一条边的情况,注意,删除一条边的时候,例如 u-->v ,那么后面v这个点的入度相应的就会减少1。对所有边都枚举一下,若有不合题意的情况,就输出结果并且break;
#include<bits/stdc++.h>
#include<queue>
#include<vector>
using namespace std;
#define ms(a) memset(a,0,sizeof(a)
const int maxn = 500+10;
queue<int>que;
vector<int>vec[maxn];
int indeg[maxn],indeg1[maxn];
int n,m,u,v,flag;
bool temp;
bool topsort()
{
while(!que.empty())
que.pop();
for(int i=1;i<=n;i++)
{
if(!indeg[i])
que.push(i);
}
int now,num=0;
while(!que.empty())
{
now=que.front();
que.pop();
num++;
for(int i=0;i<vec[now].size();i++)
{
if(--indeg[vec[now][i]]==0)
que.push(vec[now][i]);
}
}
if(num==n)
return true;
return false;
}
int main()
{
while(cin>>n>>m)
{
memset(indeg,0,sizeof(indeg));
memset(indeg1,0,sizeof(indeg1));
for(int i=1;i<=n;i++)
vec[i].clear();
for(int i=0;i<m;i++)
{
cin>>u>>v;
vec[u].push_back(v);
indeg[v]++;
indeg1[v]++;
}
temp=topsort(); //不删除边
if(temp)
{
cout<<"YES"<<endl;
continue;
}
else
{
flag = 0;
for(int i=1;i<=n;i++)
{//memcpy()拷贝函数,将indeg用indeg1重新复制,大小为sizeof(indeg1);
memcpy(indeg,indeg1,sizeof(indeg1));
if(indeg[i]>=1) //删除1条边
indeg[i]--;
if(temp = topsort())
{
flag = 1;
cout<<"YES"<<endl;
break;
}
}
}
if(flag == 0)
cout<<"NO"<<endl;
}
return 0;
}