1002. Is It Acyclic
来源:互联网 发布:淘宝韩妆小样真假 编辑:程序博客网 时间:2024/06/04 18:51
Description
Given a directed graph, decide if it is acyclic (there is no directed cycle).
Input
There are multiple test cases. The first line contains an integer T, indicating the number of test cases. Each test case begins with a line containing two integers, 1 <= n <= 100000 and 1 <= m <= 100000. n is the number of vertices (numbered from 1 to n) and m is the number of direct precedence relations between vertices. After this, there will be m lines with two integers i and j, representing that there is a directed edge from vertex i to vertex j.
Output
For each test case, print a line "It is acyclic." or "There exists a cycle.".
Sample Input
23 31 22 33 15 53 44 13 22 45 3
Sample Output
There exists a cycle.It is acyclic.
判断有向图中是否存在环,用拓扑排序,用DFS会超时;拓扑排序时,如果所有顶点都被访问到,则无环;反之有环。
此外还要注意题目中的限制条件。
#include <iostream>#include <vector>#include <list>#include <queue>using namespace std;struct Graph { vector<list<int> > adj; int v, e; int indgree[100001];// 存储顶点的入度};//初始化图void makeGraph(Graph* &g) { int m, n; cin >> m >> n; g->v = m; g->e = n; for (int i = 1; i <= g->v; ++i) { g->indgree[i] = 0; } for (int i = 1; i <= g->e; ++i) { int a, b; cin >> a >> b; g->adj[a].push_back(b); g->indgree[b]++; }}//拓扑排序void topology(Graph* &g) { queue<int> q; //用队列存储入度为0的顶点 int count = 0; for (int i = 1; i <=g->v; ++i) { if (g->indgree[i] == 0) { q.push(i); ++count; } } while (!q.empty()) { int a = q.front(); q.pop(); //遍历顶点的邻接表,每一次都将入度减一 list<int>::iterator it = g->adj[a].begin(); while (it != g->adj[a].end()) { g->indgree[*it]--; if (g->indgree[*it] == 0) { q.push(*it); count++; } *it++; } } if (count == g->v) { cout << "It is acyclic." << endl; } else cout << "There exists a cycle." << endl;}int main(int argc, const char * argv[]) { int cases; cin >> cases; for (int i = 0; i < cases; ++i) { Graph *g = new Graph; g->adj.resize(100001); makeGraph(g); topology(g); }}
0 0
- 1002. Is It Acyclic
- It is my brithday
- Is it okay?
- It is my pass
- How is it going?
- It is more excited.
- It is coming!
- Is It A Tree?
- It is my life
- It is really Awesome!
- This is it
- This is IT
- Maven... What is it?
- It is obvious today
- OBJECT WHERE IS IT?
- hdu3793 Is It Symmetric
- Is it a tree?
- is it summer ?
- 单例设计模式
- Android L中水波纹点击效果的实现
- try-catch-finally中return的执行情况
- 01-09-2015—员工管理系统完结
- linux 技巧:使用 screen 管理你的远程会话
- 1002. Is It Acyclic
- 如何启动eclipse时提示选择工作空间||删除workspace空间的目录
- 年终小结之搜房网面试题(二)
- 《OpenERP应用和开发基础》-采购业务概述
- 同步通信与异步通信区别
- 第34题 Restore IP Addresses
- 数据库问题——无法与SQL Server建立连接
- CSS中表示cellpadding和cellspacing的方法
- 【UML实践】——实战总结