1. 程式人生 > >codeforces-915D Almost Acyclic Graph(拓撲序判圈)

codeforces-915D Almost Acyclic Graph(拓撲序判圈)

連結:http://codeforces.com/problemset/problem/915/D題意:在一個有向圖中,判斷能不能至多刪除一條邊使得該圖不含圈,n<=500, m<=100000題解:列舉每一個點,讓該點的入度減一,然後拓撲序判圈程式碼:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>

using namespace std;

vector<int> G[510];
int in[510];
int indu[510];
int n, m;

bool tuopu(){
    queue<int> que;
    for(int i = 1; i<=n; i++){
        if(indu[i] == 0) que.push(i);
    }
    int cnt = 0;
    while(que.size()){
        int f = que.front();
        que.pop();
        cnt++;
        for(int i = 0; i<G[f].size(); i++){
            int v = G[f][i];
            indu[v]--;
            if(indu[v] == 0) que.push(v);
        }
    }
    if(cnt == n) return true;
    else return false;
}

int main(){
    scanf("%d%d", &n, &m);
    for(int i = 0; i<m; i++){
        int u, v;
        scanf("%d%d", &u, &v);
        G[u].push_back(v);
        in[v]++;
    }
    for(int i = 1; i<=n; i++){
        for(int j = 1; j<=n; j++) indu[j] = in[j];
        indu[i]--;
        if(tuopu() == true){
            printf("YES\n");
            return 0;
        }

    }
    printf("NO\n");

    return 0;
}