题目大意
给出一个
n
n
n个点,
m
m
m条边的有向图,
问是否可以再删除一条边之后,图中不会出现环。
时间限制
1s
数据范围
n
≤
500
n\le500
n≤500
m
≤
1
0
5
m\le10^5
m≤105
题解
判断有向无环图,最简单的方法就是拓扑排序。
每一次拓扑排序的时间复杂度是
O
(
m
)
O\pod{m}
O(m),显然不能直接枚举删除哪条边。
不过,可以发现,有些便无论是否被删除它都不会对答案造成影响,比如说本身就不在环里面的边。
先进行一次拓扑排序,如果没有环,就直接输出YES
,如果有环,那么图中必然还会剩余一些边,
那么就枚举这些边中连进点度数为
1
1
1的边。
这样枚举的边就明显减少,可以通过此题。
Code
//#pragma GCC optimize (2)
//#pragma G++ optimize (2)
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
#include <vector>
#include <queue>
#define G getchar
#define ll long long
using namespace std;
ll read()
{
char ch;
for(ch = G();(ch < '0' || ch > '9') && ch != '-';ch = G());
ll n = 0 , w;
if (ch == '-')
{
w = -1;
ch = G();
} else w = 1;
for(;'0' <= ch && ch <= '9';ch = G())n = (n<<1)+(n<<3)+ch-48;
return n * w;
}
const int N = 100003;
int n , m , x , y , cnt;
int nxt[N] , lst[N] , to[N] , tot;
int xx , yy;
int l , r , q[N];
int d[503] , g[503];
bool ans , bz[503];
void ins (int x , int y)
{
tot++;
d[y]++;
to[tot] = y;
nxt[tot] = lst[x];
lst[x] = tot;
}
bool bfs()
{
l = 0;
r = 0;
memcpy(g , d , sizeof(g));
g[yy]--;
for (int i = 1 ; i <= n; i++)
if (g[i] == 0)
{
r++;
q[r] = i;
}
for ( ; l < r ; )
{
l++;
x = q[l];
for (int i = lst[x] ; i ; i = nxt[i])
if (x != xx || to[i] != yy)
{
g[to[i]]--;
if (g[to[i]] == 0)
{
r++;
q[r] = to[i];
}
}
}
return (l == n);
}
int main()
{
//freopen("d.in","r",stdin);
//freopen("d.out","w",stdout);
n = read();
m = read();
for (int i = 0 ; i < m ; i++)
{
x = read();
y = read();
ins(x , y);
}
memset(bz , 0 , sizeof(bz));
ans = bfs();
for (int i = 1 ; i <= n ; i ++)
if (g[i] == 1) bz[i] = 1;
for (int i = 1 ; i <= n ; i ++)
{
xx = i;
for (int j = lst[i] ; j ; j = nxt[j])
{
yy = to[j];
if (bz[yy] && bfs())
{
ans = 1;
break;
}
}
if (ans) break;
}
if (ans) puts("YES"); else puts("NO");
return 0;
}