[CF915D] Almost Acyclic Graph

[CF915D] Almost Acyclic Graph - 拓扑排序

Description

给定有向图 (n le 500, m le 10^5),最多删去一条边是否能使得这个图变成有向无环图?

Solution

直观但麻烦的想法:随便找一个环,暴力枚举删除环上的一条边,再检验

考虑枚举让某个点删去一条边,但是不用真的删,只需要把它的入度 -1 即可,这样相当于删去了任意一条,让这个点更早地称为拓扑排序过程中的可选点

#include <bits/stdc++.h>
using namespace std;

const int N = 505;
vector<int> g[N];
int n, m, d[N], a[N];

bool check()
{
    int ans = 0;
    queue<int> que;
    for (int i = 1; i <= n; i++)
        if (d[i] == 0)
            que.push(i);
    while (que.size())
    {
        int p = que.front();
        que.pop();
        ++ans;
        for (int q : g[p])
            if (--d[q] == 0)
                que.push(q);
    }
    return ans == n;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int u, v;
        cin >> u >> v;
        g[u].push_back(v);
        a[v]++;
    }
    for (int i = 1; i <= n; i++)
    {
        if (a[i] == 0)
            continue;
        for (int j = 1; j <= n; j++)
            d[j] = a[j] - (i == j);
        if (check())
        {
            cout << "YES";
            return 0;
        }
    }
    cout << "NO";
}
原文地址:https://www.cnblogs.com/mollnn/p/14366197.html