当前位置: 移动技术网 > 移动技术>移动开发>Android > T46449 有向图无环(DAG)的判定 (dfs)

T46449 有向图无环(DAG)的判定 (dfs)

2020年07月23日  | 移动技术网移动技术  | 我要评论

T46449 有向图无环(DAG)的判定
提交
172
通过
69
时间限制
1.00s
内存限制
125.00MB
提交答案
加入收藏
题目提供者
BDFZ-OIER
难度
暂无评定
历史分数
100
提交记录
标签
暂无标签
进入讨论版
相关讨论
暂无
推荐题目
展开
题目描述
给定无权有向图G(V,E),请判断G是否是一个有向无环图(DAG)。

*在有向图中,若存在B边,则存在环。

输入格式
第一行包含两个整数N、M,表示该图共有N个结点和M条有向边。(N <= 5000,M <= 200000)

接下来M行,每行包含2个整数{u,v},表示有一条有向边(u,v)

输出格式
有环输出“not DAG”,无环输出“DAG”

输入输出样例
输入 #1复制
5 7
1 2
1 5
2 3
3 1
3 2
4 1
4 5
输出 #1复制
not DAG

#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <queue>
#include <climits>
#include <stack>
#include <map>
#include <cmath>
#include <set>
using namespace std;
typedef long long ll;
int n,m;
const int maxn=5005;
int post[maxn],pre[maxn];
vector<int>adj[maxn];
template<class T>
void read(T &x){
    ll f=1;
    x=0;
    char c=getchar();
    while(!isdigit(c)){
        f=-1;
        c=getchar();
    }
    while(isdigit(c)){
        x=x*10+c-48;
        c=getchar();
    }
    x*=f;
}
template<class T>
void write(T x){
    if(x<0){
        putchar('-');
        x=-x;
    }
    if(x>9){
        write(x/10);
    }
    putchar(x%10+'0');
}
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int flag=1,t;
void dfs(int u){
   pre[u]=++t;
   for(auto i:adj[u]){
       if(!pre[i]){
           dfs(i);
       }
       else if(!post[i]){
           flag=0;
       }
   }
   post[u]=++t;
}
int main()
{  
    
    read(n);
    read(m);
    int a,b;
    for(int i=0;i<m;i++){
        read(a),read(b);
        adj[a].push_back(b);
    }
    for(int i=1;i<=n;i++){
        if(!pre[i])dfs(i);
    }
    if(flag)printf("DAG");
    else printf("not DAG");
    return 0;
}

本文地址:https://blog.csdn.net/Gyibin/article/details/107448854

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网