题目大意
给出一个nnn个点,mmm条边的有向图,
问是否可以再删除一条边之后,图中不会出现环。
时间限制
1s
数据范围
n≤500n\le500n≤500
m≤105m\le10^5m≤105
题解
判断有向无环图,最简单的方法就是拓扑排序。
每一次拓扑排序的时间复杂度是O(m)O\pod{m}O(m),显然不能直接枚举删除哪条边。
不过,可以发现,有些便无论是否被删除它都不会对答案造成影响,比如说本身就不在环里面的边。
先进行一次拓扑排序,如果没有环,就直接输出YES,如果有环,那么图中必然还会剩余一些边,
那么就枚举这些边中连进点度数为111的边。
这样枚举的边就明显减少,可以通过此题。
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;
}
该博客讨论了一种有向图的问题,即在给定的有向图中,判断是否能通过删除一条边使得图中不出现环。博主提出了使用拓扑排序的方法来解决,首先尝试直接进行拓扑排序,若成功则图原本无环,输出YES;若存在环,则枚举度数为1的节点的出边,再次尝试拓扑排序,找到能消除环的边。代码使用C++实现,通过优化减少了枚举次数,提高了效率。
208

被折叠的 条评论
为什么被折叠?



